class CommonHelper < ActiveRecord::Base

  def self.getAvhResult(rubySocket,cmd,date_cmd)
    begin
      avResultStr = SocketHelper.getCR(rubySocket,cmd,false)
      #测试专用
      #logger.error "---No.1---"
      #logger.error avResultStr
      if avResultStr.index(date_cmd[0,5])==nil
        #不是以查询日期开头的结构都视为无效结果
        if avResultStr.index("\n")
          avResultStr = avResultStr[0,avResultStr.index("\n")]
        end
        if avResultStr.index("\r")
          avResultStr = avResultStr[0,avResultStr.index("\r")]
        end
        if avResultStr.index("\t")
          avResultStr = avResultStr[0,avResultStr.index("\t")]
        end

        if avResultStr.index("失败")
          restring = "失败 "+avResultStr
        elsif avResultStr.index(date_cmd[2..4])
          restring = "失败 该日没有航班,可以选择"+avResultStr[avResultStr.index(date_cmd[2..4])-2,5]
        elsif avResultStr.index("timeout")
          restring = "失败 连接放大器超时."
        elsif avResultStr.index("socket is null") || avResultStr==""
          restring = "失败 访问放大器失败."
        else
          restring = "失败 返回信息:"+avResultStr
        end
      else
        #转换字符 去掉第一行的日期信息和最后一行以**开头的其他信息
        restring = CommonHelper.translateAvhResult(avResultStr)
        #翻页
        pn_sum = 6
        pn_sum = 11 if cmd.index("SHA") && cmd.index("PEK")
        pn_i = 2
        while(pn_i <= pn_sum)
          avResultStr = SocketHelper.getCR(rubySocket,"pn",false)
          if avResultStr.index(date_cmd[0,5])==nil
            #当天航班翻页到头以后就显示下一天的航班了,需要给用户一个提示
            #logger.error "---No."+pn_i.to_s+" OUT!!!!!---"
            break
          else
            #logger.error "---No."+pn_i.to_s+"---"
            #logger.error avResultStr
            restring << CommonHelper.translateAvhResult(avResultStr)
          end
          pn_i += 1
        end
      end
      #去掉最后面的航站楼信息 例如 T2 T2 或者 3  2
      restring = restring.gsub(/  T\d T\d/,"")
      restring = restring.gsub(/  \d  \d/,"")
      #logger.error restring
      return restring.squish
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getAvhResult",e,"error")
      rubySocket.close
      rubySocket=nil
      return ""
    end
  end

  #保存订单记录
  def self.saveOrder(uid,cid,owner_id,employee_no,pnr,fly_date,fly_time,link_man,link_tel,insurance_number,send_address,send_date,send_time,send_request,order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,price_sum,seat,airways_code,web,group,inter)
    begin
      transaction do #事务
        order = Order.new
        order.creator_id = uid.to_i
        order.last_editer_id = uid.to_i
        order.owner_id = owner_id.to_i
        order.customer_id = cid.to_i
        order.pnr = pnr
        order.fly_date = fly_date if fly_date
        order.fly_time = fly_time if fly_time
        order.link_man = link_man if link_man
        order.link_tel = link_tel if link_tel
        order.insurance_number = insurance_number.to_i if insurance_number
        order.send_address = send_address if send_address
        #添加新的送票地址
        if send_address && send_address!=""
          #查看是否是新的address，是新的就保存到客户地址表中
          c_address = CustomerAddress.find(:first,:conditions=>["customer_id=? and address=?",cid,send_address])
          if c_address==nil
            c_address = CustomerAddress.new
            c_address.address = send_address
            c_address.customer_id = cid.to_i
            c_address.save
          end
        end
        #COF 确认日期
        affirm_date = Time.new.strftime("%Y-%m-%d") if affirm_date==nil
        order.affirm_date = affirm_date
        order.send_date = send_date if send_date
        order.send_time = send_time
        order.send_request = send_request
        order.order_request = order_request
        order.jj_address = jj_address
        order.jj_time = jj_time if jj_time
        order.jj_request = jj_request
        order.tktl_date = tktl_date if tktl_date
        order.tktl_time = tktl_time
        if fix_type && fix_type=="LL"
          #申请单
          order.status = Constants::ORDER_STATUS_SQD
        else
          order.status = Constants::ORDER_STATUS_YDD
        end
        order.price_sum = price_sum.to_i #订单实际金额
        order.seat = seat.to_i if seat   #乘客人数
        order.order_no = getNewOrderNo(employee_no)
        order.airways_code = airways_code if airways_code
        if web && web!=""
          order.web = "网络订单"
          order.trx_status = Constants::WEB_ORDER_STATUS_DDZF
        end
        if group && group!=""
          order.group = "团体订单"
        end
        if inter && inter!=""
          order.international = "国际订单"
        end
        if order.save
          return order.id
        end
      end
      return false
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","saveOrder",e,"error")
      return false
    end
  end

  #保存票记录
  def self.saveTicket(cid,pnr,orderid,ticket_no,airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price,price_F,point,passenger_name,human_type,id_card,birthday,insurance_number,status,trip_type)
    begin
      transaction do #事务
        #logger.error ">>>>>>>> saveTicket >>>>>>>>"
        price = price.to_i

        ticket = Ticket.new
        ticket.pnr = pnr
        ticket.order_id = orderid
        ticket.ticket_no = ticket_no if ticket_no
        ticket.customer_id = cid.to_i
        ticket.air_no = airNo
        ticket.fromto = fromto
        ticket.fly_date = fly_date if fly_date
        #ticket.fly_date = Time.new.strftime("%y-%m-%d")
        ticket.fly_time = fly_time
        ticket.arr_time = arr_time
        ticket.plane_type = plane_type
        ticket.position = position
        ticket.status_type = status_type if status_type
        if passenger_name=="未指定人员"
          ticket.passenger_id = 1
        else
          #如果是儿童，则从中提取出生日期
          if passenger_name.index("CHD(")
            birthday = passenger_name[passenger_name.index("(")+1..passenger_name.index(")")-1]
            birthday = "20"+birthday[5,2]+"-"+getMonthByStr(birthday[2,3])+"-"+birthday[0,2]
            passenger_name = passenger_name[0,passenger_name.index("CHD(")]
            price = getChdPrice(airNo[0,2],fromto)
            human_type="儿童"
          end
          passenger = Customer.find(:first,:conditions => ["name=? and card=? and is_locked<>1",passenger_name,id_card])
          if passenger==nil
            #不是常旅客
            passenger = Customer.new
            passenger.name = passenger_name
            passenger.card = id_card
            passenger.birthday = birthday if birthday
            passenger.customer_type_id = 1 #1表示为常旅客
            passenger.save
          elsif birthday && birthday.index("-")
            #是常旅客，有生日信息则更新生日信息
            passenger.birthday = birthday
            passenger.save
          end
          ticket.passenger_id = passenger.id
        end
        #去掉个位数金额
        ticket.price = getRightPrice(price)
        fuel = getFuelTax(fromto)
        #如果出生日期有数据，则是儿童票  儿童票没有机建 燃油也是一半
        #today = Time.new.strftime("%Y-%m-%d")
        if human_type=="婴儿"
          #if birthday && birthday.index("-")
          #if birthday.to_date>(today.to_date-365)
          ticket.airdrome_tax = 0
          fuel = 0
        elsif human_type=="儿童"
          #儿童不收机建费 燃油费一半
          ticket.airdrome_tax = 0
          fuel = getRightPrice(fuel/2)
        else
          ticket.airdrome_tax = getPlaneTax(plane_type) if plane_type
        end
        ticket.fuel_tax = fuel
        ticket.ticket_type = human_type
        ticket.insurance_number = insurance_number.to_i if insurance_number
        ticket.price_F = price_F.to_i if price_F
        ticket.total_price = ticket.price + (Constants::DEFAULT_INSURANCE_PRICE*ticket.insurance_number) + ticket.airdrome_tax + ticket.fuel_tax - ticket.price_F
        ticket.point = point.to_i if point
        ticket.status = status if status
        ticket.trip_type = trip_type if trip_type
        #查询符合条件的代理费政策
        policy = getPolicy(nil,airNo,fromto,fly_date,position,trip_type)
        if policy
          ticket.rake_off = policy.rake_off
          ticket.policy_id = policy.id
        end
        if ticket.save
          return ticket.id
        end
      end
      return false
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","saveTicket",e,"error")
      return false
    end
  end

  #多人 单程
  def self.saveMulOrderTicket(uid,cid,owner_id,pnr,link_man,link_tel,send_address,send_date,send_time,send_request,
      order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,web,group,
      nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
      airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price)
    begin
      logger.error  "=============CommonHelper saveMulOrderTicket 多人 单程==================="
      logger.error  uid
      logger.error  cid

      transaction do #事务
        seat = seat.to_i
        price = price.to_i
        price_F = 0
        chd_price_F = 0
        baby_price_F = 0
        insurance_sum = Constants::DEFAULT_INSURANCE_PRICE*i_number.to_i #保险总金额，在这里i_number是订单中保险的总数
        user = User.find_by_id(uid)
        customer = Customer.find_by_id(cid)

        logger.error  "用户="+user.user_name
        logger.error  "客户="+customer.name
        logger.error  "座位数="+seat.to_s
        logger.error  "单人价="+price.to_s
        logger.error  "保险份数="+i_number.to_s

        baby_price = getBabyPrice(airNo[0,2],fromto)
        logger.error "航段#{airNo}的baby婴儿票价="+baby_price.to_s
        chd_price = getChdPrice(airNo[0,2],fromto)
        logger.error "航段#{airNo}的chd儿童票价="+chd_price.to_s

        #如果有客户记录，则添加客户的积分、累计消费等数据
        customer_type = customer.customer_type
        return_cash = customer_type.return_cash
        logger.error  "返利类型return_cash="+return_cash
        return_rate = customer_type.return_rate
        logger.error  "返利比率return_rate="+return_rate.to_s
        plus = customer_type.plus
        plus_rate = customer_type.plus_rate
        #成人票返利
        point = price*return_rate/100
        #logger.error  "返利值point="+point.to_s
        point = getPlusRatePoint(plus,plus_rate,point)
        if return_cash=="返现"
          #返现 当前消费只计算用户实际支付的金额
          price_F = point
          point = 0
        end
        #儿童票返利
        chd_point = chd_price*return_rate/100
        #logger.error  "儿童票返利值chd_point="+chd_point.to_s
        chd_point = getPlusRatePoint(plus,plus_rate,chd_point)
        if return_cash=="返现"
          chd_price_F = chd_point
          chd_point = 0
        end
        #婴儿票返利
        baby_point = chd_price*return_rate/100
        #logger.error  "婴儿票返利值baby_point="+baby_point.to_s
        baby_point = getPlusRatePoint(plus,plus_rate,baby_point)
        if return_cash=="返现"
          baby_price_F = baby_point
          baby_point = 0
        end

        #today = Time.new.strftime("%Y-%m-%d")
        #计算总价格
        airdrome_tax = getPlaneTax(plane_type)
        fuel_tax = getFuelTax(fromto)
        logger.error "机建="+airdrome_tax.to_s
        logger.error "燃油="+fuel_tax.to_s
        
        price_sum = 0
        if group && group!=""
          for_length = 0
          price_sum = seat*(price - price_F + fuel_tax + airdrome_tax)
        else
          for_length = seat-1
          birthdayArr = birthdayString.split(",")
          humanTypeArr = humanTypeString.split(",")
          for i in 0..for_length
            logger.error "---循环---"+i.to_s
            human_type = humanTypeArr[i]
            logger.error human_type
            if human_type=="婴儿"
              #if birthdayArr[i] && birthdayArr[i].index("-")
              #if birthdayArr[i].to_date>(today.to_date-365)
              #婴儿 无机建 无燃油
              price_sum += baby_price - baby_price_F
            elsif human_type=="儿童"
              #儿童
              price_sum += chd_price - chd_price_F
              price_sum += getRightPrice(fuel_tax/2)
            else
              price_sum += price - price_F
              price_sum += fuel_tax
              price_sum += airdrome_tax
            end
          end
        end
        price_sum = price_sum + insurance_sum #（每张票的票面价+税费）乘以座位数+保险总金额=订单总金额
        logger.error  "订单总金额  price_sum="+price_sum.to_s

        #保存订单
        orderid = saveOrder(uid,cid,owner_id,user.employee_no,pnr,fly_date,fly_time,link_man,link_tel,i_number,send_address,send_date,send_time,send_request,order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,price_sum,seat,airNo[0,2],web,group,"")
        if orderid
          logger.error "orderid="+orderid.to_s
          go = true
          nameArr = nameString.split(",")
          humanTypeArr = humanTypeString.split(",")
          cardArr = cardString.split(",")
          birthdayArr = birthdayString.split(",")
          insuranceArr = insuranceString.split(",")
          for i in 0..for_length
            human_type = ""
            id_card = ""
            birthday = ""
            insurance_number = 0

            passenger_name = nameArr[i]
            human_type = humanTypeArr[i] if humanTypeArr[i]
            id_card = cardArr[i] if cardArr[i]
            birthday = birthdayArr[i] if birthdayArr[i]
            insurance_number = insuranceArr[i].to_i if insuranceArr[i]

            logger.error "乘客="+passenger_name
            logger.error "类型="+human_type
            logger.error "证件号="+id_card
            logger.error "出生日期="+birthday
            logger.error "保险份数="+insurance_number.to_s

            if human_type=="婴儿"
              #if birthday.to_date>(today.to_date-365)
              t_price = baby_price
              t_price_F = baby_price_F
              t_point = baby_point
            elsif human_type=="儿童"
              t_price = chd_price
              t_price_F = chd_price_F
              t_point = chd_point
            else
              t_price = price
              t_price_F = price_F
              t_point = point
            end
            if !saveTicket(cid,pnr,orderid,"",airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,t_price,t_price_F,t_point,passenger_name,human_type,id_card,birthday,insurance_number,status,trip_type)
              logger.error "-----保存乘客"+passenger_name+"的"+airNo+"票记录失败-----"
              go = false
              break
            end
          end
          logger.error go
          if go
            return true
          end
        end
      end
      logger.error  "CommonHelper saveMulOrderTicket 结束"
      return false
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","saveMulOrderTicket",e,"error")
      return false
    end
  end

  #多人 返程 联程
  def self.saveMulOrderTicket2(uid,cid,owner_id,pnr,link_man,link_tel,send_address,send_date,send_time,send_request,
      order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,web,group,
      nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
      airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price,
      airNo2,fromto2,fly_date2,fly_time2,arr_time2,plane_type2,position2,status_type2,price2)
    begin
      logger.error  "=============CommonHelper saveMulOrderTicket2 多人 返程 联程==================="
      logger.error  uid
      logger.error  cid

      transaction do #事务
        seat = seat.to_i
        price = price.to_i
        price2 = price2.to_i

        airdrome_tax = getPlaneTax(plane_type)
        fuel_tax = getFuelTax(fromto)
        airdrome_tax2 = getPlaneTax(plane_type2)
        fuel_tax2 = getFuelTax(fromto2)
        if humanTypeString.index("婴儿")
          baby_price = getBabyPrice(airNo[0,2],fromto)
          logger.error "航段#{airNo}的baby婴儿票价="+baby_price.to_s
          baby_price2 = getBabyPrice(airNo2[0,2],fromto2)
          logger.error "航段#{airNo2}的baby婴儿票价="+baby_price2.to_s
          baby_price_sum = baby_price + baby_price2
          logger.error  "婴儿单人总价="+baby_price_sum.to_s
        end
        if humanTypeString.index("儿童")
          chd_fuel_tax = getRightPrice(fuel_tax/2)   #儿童燃油税是成人的一半
          chd_fuel_tax2 = getRightPrice(fuel_tax2/2)

          chd_price = getChdPrice(airNo[0,2],fromto)
          logger.error "航段#{airNo}的chd儿童票价="+chd_price.to_s
          chd_price2 = getChdPrice(airNo2[0,2],fromto2)
          logger.error "航段#{airNo2}的chd儿童票价="+chd_price2.to_s
          chd_price_sum = chd_price + chd_price2
          logger.error  "儿童单人总价="+chd_price_sum.to_s
        end

        hum_price_sum = price + price2
        price_F = 0
        price_F2 = 0
        chd_price_F = 0
        chd_price_F2 = 0
        baby_price_F = 0
        baby_price_F2 = 0
        insurance_sum = Constants::DEFAULT_INSURANCE_PRICE*i_number.to_i #保险总金额，在这里i_number是订单中保险的总数
        user = User.find_by_id(uid)
        customer = Customer.find_by_id(cid)

        logger.error  "用户="+user.user_name
        logger.error  "客户="+customer.name
        logger.error  "座位数="+seat.to_s
        logger.error  "单人总价="+hum_price_sum.to_s
        logger.error  "单程保险总份数="+i_number.to_s

        #查看是否有特价
        if airNo[0,2]==airNo2[0,2]
          airways_code = airNo[0,2]
          airways = Airways.find_by_code(airways_code)
          if airways
            fromAirport = Airport.find_by_code(fromto[0,3])
            midAirport = Airport.find_by_code(fromto[3,3])
            toAirport = Airport.find_by_code(fromto2[3,3])
            lcSpecialPrice = ZjlyPrice.find(:first,:conditions=>["trip_type='"+trip_type+"' and airways_id=? and from_id=? and mid_id=? and to_id=? and position=? and (start_date is null or start_date<?) and (end_date is null or end_date>?)",airways.id,fromAirport.id,midAirport.id,toAirport.id,position,fly_date,fly_date],:order=>"price desc")
            if lcSpecialPrice
              logger.error  airways_code+"特价="+lcSpecialPrice.price.to_s
              special_price = lcSpecialPrice.price.to_i
              hum_price_sum = special_price
            end
          end
        end
        #如果有客户记录，则添加客户的积分、累计消费等数据
        customer_type = customer.customer_type
        return_cash = customer_type.return_cash
        logger.error  "返利类型return_cash="+return_cash
        return_rate = customer_type.return_rate
        logger.error  "返利比率return_rate="+return_rate.to_s
        plus = customer_type.plus
        plus_rate = customer_type.plus_rate
        #成人票返利
        point = hum_price_sum*return_rate/100
        logger.error  "返利值point="+point.to_s
        point = getPlusRatePoint(plus,plus_rate,point)
        if return_cash=="返现"
          #返现 当前消费只计算用户实际支付的金额
          price_F = point
          point = 0
        end
        if chd_price_sum
          #儿童票返利
          chd_point = chd_price_sum*return_rate/100
          logger.error  "儿童票返利值chd_point="+chd_point.to_s
          chd_point = getPlusRatePoint(plus,plus_rate,chd_point)
          if return_cash=="返现"
            chd_price_F = chd_point
            chd_point = 0
          end
        end
        if baby_price_sum
          #婴儿票返利
          baby_point = baby_price_sum*return_rate/100
          logger.error  "婴儿票返利值baby_point="+baby_point.to_s
          baby_point = getPlusRatePoint(plus,plus_rate,baby_point)
          if return_cash=="返现"
            baby_price_F = baby_point
            baby_point = 0
          end
        end
        #today = Time.new.strftime("%Y-%m-%d")
        #计算总价格
        price_sum = 0
        if group && group!=""
          for_length = 0
          price_sum = seat*(hum_price_sum - price_F + fuel_tax + fuel_tax2 + airdrome_tax + airdrome_tax2)
        else
          for_length = seat-1
          birthdayArr = birthdayString.split(",")
          humanTypeArr = humanTypeString.split(",")
          for i in 0..for_length
            human_type = humanTypeArr[i]
            if human_type=="婴儿"
              #if birthdayArr[i] && birthdayArr[i].index("-")
              #if birthdayArr[i].to_date>(today.to_date-365)
              price_sum += baby_price_sum - baby_price_F
            elsif human_type=="儿童"
              price_sum += chd_price_sum - chd_price_F
              price_sum += chd_fuel_tax + chd_fuel_tax2
            else
              price_sum += hum_price_sum - price_F
              price_sum += fuel_tax + fuel_tax2
              price_sum += airdrome_tax + airdrome_tax2
            end
          end
        end
        price_sum = price_sum + insurance_sum #（每张票的票面价+税费）乘以座位数+保险总金额=订单总金额
        logger.error  "订单总金额  price_sum="+price_sum.to_s

        #保存订单
        orderid = saveOrder(uid,cid,owner_id,user.employee_no,pnr,fly_date,fly_time,link_man,link_tel,i_number.to_i,send_address,send_date,send_time,send_request,order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,price_sum,seat,airNo[0,2],web,group,"")
        if orderid
          logger.error "orderid="+orderid.to_s
          #是否是特殊联程价格，特殊联程价格单独处理
          if special_price
            price = special_price
            price2 = 0
            if return_cash=="返现"
              price_F = point
              point = 0
            end
            price_F2 = 0
            point2 = 0
          else
            point = price*return_rate/100
            point = getPlusRatePoint(plus,plus_rate,point)
            point2 = price2*return_rate/100
            point2 = getPlusRatePoint(plus,plus_rate,point2)
            if return_cash && return_cash=="返现"
              price_F = point
              point = 0
              price_F2 = point2
              point2 = 0
            end
          end
          if chd_price_sum
            #儿童
            chd_point = chd_price*return_rate/100
            chd_point = getPlusRatePoint(plus,plus_rate,chd_point)
            chd_point2 = chd_price2*return_rate/100
            chd_point2 = getPlusRatePoint(plus,plus_rate,chd_point2)
            if return_cash && return_cash=="返现"
              chd_price_F = chd_point
              chd_point = 0
              chd_price_F2 = chd_point2
              chd_point2 = 0
            end
          end
          if baby_price_sum
            #婴儿
            baby_point = baby_price*return_rate/100
            baby_point = getPlusRatePoint(plus,plus_rate,baby_point)
            baby_point2 = baby_price2*return_rate/100
            baby_point2 = getPlusRatePoint(plus,plus_rate,baby_point2)
            if return_cash && return_cash=="返现"
              baby_price_F = baby_point
              baby_point = 0
              baby_price_F2 = baby_point2
              baby_point2 = 0
            end
          end
          go = true
          nameArr = nameString.split(",")
          humanTypeArr = humanTypeString.split(",")
          cardArr = cardString.split(",")
          birthdayArr = birthdayString.split(",")
          insuranceArr = insuranceString.split(",")
          for i in 0..for_length
            human_type = ""
            id_card = ""
            birthday = ""
            insurance_number = 0

            passenger_name = nameArr[i]
            human_type = humanTypeArr[i] if humanTypeArr[i]
            id_card = cardArr[i] if cardArr[i]
            birthday = birthdayArr[i] if birthdayArr[i]
            insurance_number = insuranceArr[i].to_i if insuranceArr[i]

            logger.error "乘客="+passenger_name
            logger.error "类型="+human_type
            logger.error "证件号="+id_card
            logger.error "出生日期="+birthday
            logger.error "保险份数="+insurance_number.to_s

            if human_type=="婴儿"
              #if birthday.to_date>(today.to_date-365)
              t_price = baby_price
              t_price_F = baby_price_F
              t_point = baby_point
              t_price2 = baby_price2
              t_price_F2 = baby_price_F2
              t_point2 = baby_point2
            elsif human_type=="儿童"
              t_price = chd_price
              t_price_F = chd_price_F
              t_point = chd_point
              t_price2 = chd_price2
              t_price_F2 = chd_price_F2
              t_point2 = chd_point2
            else
              t_price = price
              t_price_F = price_F
              t_point = point
              t_price2 = price2
              t_price_F2 = price_F2
              t_point2 = point2
            end
            if saveTicket(cid,pnr,orderid,"",airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,t_price,t_price_F,t_point,passenger_name,human_type,id_card,birthday,insurance_number,status,trip_type)
              if !saveTicket(cid,pnr,orderid,"",airNo2,fromto2,fly_date2,fly_time2,arr_time2,plane_type2,position2,status_type2,t_price2,t_price_F2,t_point2,passenger_name,human_type,id_card,birthday,0,status,trip_type)
                logger.error "-----保存乘客"+passenger_name+"的"+airNo2+"票记录失败-----"
                go = false
                break
              end
            else
              logger.error "-----保存乘客"+passenger_name+"的"+airNo+"票记录失败-----"
              go = false
              break
            end
          end
          logger.error go
          if go
            return true
          end
        end
      end
      logger.error  "CommonHelper saveMulOrderTicket2 结束"
      return false
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","saveMulOrderTicket2",e,"error")
      return false
    end
  end

  #多人 返程+联程
  def self.saveMulOrderTicket3(uid,cid,owner_id,pnr,link_man,link_tel,send_address,send_date,send_time,send_request,
      order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,web,group,
      nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
      airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price,
      airNo2,fromto2,fly_date2,fly_time2,arr_time2,plane_type2,position2,status_type2,price2,
      airNo3,fromto3,fly_date3,fly_time3,arr_time3,plane_type3,position3,status_type3,price3,
      airNo4,fromto4,fly_date4,fly_time4,arr_time4,plane_type4,position4,status_type4,price4)
    begin
      logger.error  "=============CommonHelper saveMulOrderTicket3 多人 返程+联程==================="
      logger.error  uid
      logger.error  cid

      transaction do #事务
        seat = seat.to_i
        price = price.to_i
        price2 = price2.to_i
        price3 = price3.to_i
        price4 = price4.to_i

        airdrome_tax = getPlaneTax(plane_type)
        airdrome_tax2 = getPlaneTax(plane_type2)
        airdrome_tax3 = getPlaneTax(plane_type3)
        airdrome_tax4 = getPlaneTax(plane_type4)
        fuel_tax = getFuelTax(fromto)  #返程时燃油税相同
        fuel_tax2 = getFuelTax(fromto2)
        fuel_tax3 = getFuelTax(fromto3)
        fuel_tax4 = getFuelTax(fromto4)
        
        if humanTypeString.index("婴儿")
          baby_price = getBabyPrice(airNo[0,2],fromto)
          logger.error "航段#{airNo}的baby婴儿票价="+baby_price.to_s
          baby_price2 = getBabyPrice(airNo2[0,2],fromto2)
          logger.error "航段#{airNo2}的baby婴儿票价="+baby_price2.to_s
          baby_price3 = getBabyPrice(airNo3[0,2],fromto3)
          logger.error "航段#{airNo3}的baby婴儿票价="+baby_price3.to_s
          baby_price4 = getBabyPrice(airNo4[0,2],fromto4)
          logger.error "航段#{airNo4}的baby婴儿票价="+baby_price4.to_s
          baby_price_sum = baby_price + baby_price2 + baby_price3 + baby_price4
          logger.error  "婴儿单人总价="+baby_price_sum.to_s
        end
        if humanTypeString.index("儿童")
          chd_fuel_tax = getRightPrice(fuel_tax/2)   #儿童燃油税是成人的一半
          chd_fuel_tax2 = getRightPrice(fuel_tax2/2)

          chd_price = getChdPrice(airNo[0,2],fromto)
          logger.error "航段#{airNo}的chd儿童票价="+chd_price.to_s
          chd_price2 = getChdPrice(airNo2[0,2],fromto2)
          logger.error "航段#{airNo2}的chd儿童票价="+chd_price2.to_s
          chd_price3 = getChdPrice(airNo3[0,2],fromto3)
          logger.error "航段#{airNo3}的chd儿童票价="+chd_price3.to_s
          chd_price4 = getChdPrice(airNo4[0,2],fromto4)
          logger.error "航段#{airNo4}的chd儿童票价="+chd_price4.to_s
          chd_price_sum = chd_price + chd_price2 + chd_price3 + chd_price4
          logger.error  "儿童单人总价="+chd_price_sum.to_s
        end

        hum_price_sum = price + price2 + price3 + price4
        price_F = 0
        price_F2 = 0
        price_F3 = 0
        price_F4 = 0
        chd_price_F = 0
        chd_price_F2 = 0
        chd_price_F3 = 0
        chd_price_F4 = 0
        baby_price_F = 0
        baby_price_F2 = 0
        baby_price_F3 = 0
        baby_price_F4 = 0
        insurance_sum = Constants::DEFAULT_INSURANCE_PRICE*i_number.to_i #保险总金额，在这里i_number是订单中保险的总数
        user = User.find_by_id(uid)
        customer = Customer.find_by_id(cid)

        logger.error  "用户="+user.user_name
        logger.error  "客户="+customer.name
        logger.error  "座位数="+seat.to_s
        logger.error  "单人价="+hum_price_sum.to_s
        logger.error  "单程保险总份数="+i_number.to_s

        #查看是否有特价
        airways_code = airNo[0,2]
        airways = Airways.find_by_code(airways_code)
        if airways
          fromAirport = Airport.find_by_code(fromto[0,3])
          midAirport = Airport.find_by_code(fromto[3,3])
          toAirport = Airport.find_by_code(fromto2[3,3])
          wflcSpecialPrice = ZjlyPrice.find(:first,:conditions=>["trip_type='联程往返' and airways_id=? and from_id=? and mid_id=? and to_id=? and position=? and (start_date is null or start_date<=?) and (end_date is null or end_date>=?)",airways.id,fromAirport.id,midAirport.id,toAirport.id,position,fly_date,fly_date],:order=>"price desc")
          if wflcSpecialPrice
            logger.error  airways_code+"联程往返 特价="+wflcSpecialPrice.price.to_s
            special_price = wflcSpecialPrice.price.to_i
            hum_price_sum = special_price
          else
            #去程
            lcSpecialPrice = ZjlyPrice.find(:first,:conditions=>["trip_type='联程' and airways_id=? and from_id=? and mid_id=? and to_id=? and position=? and (start_date is null or start_date<=?) and (end_date is null or end_date>=?)",airways.id,fromAirport.id,midAirport.id,toAirport.id,position,fly_date,fly_date],:order=>"price desc")
            if lcSpecialPrice
              logger.error  airways_code+"特价="+lcSpecialPrice.price.to_s
              special_price1 = lcSpecialPrice.price.to_i
              hum_price_sum = special_price1 + price3 + price4
            end
            #回程
            lcSpecialPrice = ZjlyPrice.find(:first,:conditions=>["trip_type='联程' and airways_id=? and from_id=? and mid_id=? and to_id=? and position=? and (start_date is null or start_date<=?) and (end_date is null or end_date>=?)",airways.id,toAirport.id,midAirport.id,fromAirport.id,position,fly_date,fly_date],:order=>"price desc")
            if lcSpecialPrice
              logger.error  airways_code+"特价="+lcSpecialPrice.price.to_s
              special_price2 = lcSpecialPrice.price.to_i
              hum_price_sum = special_price2 - price3 - price4
            end
          end
        end

        #如果有客户记录，则添加客户的积分、累计消费等数据
        customer_type = customer.customer_type
        return_cash = customer_type.return_cash
        logger.error  "返利类型return_cash="+return_cash
        return_rate = customer_type.return_rate
        logger.error  "返利比率return_rate="+return_rate.to_s
        plus = customer_type.plus
        plus_rate = customer_type.plus_rate
        #成人票返利
        point = hum_price_sum*return_rate/100
        logger.error  "返利值point="+point.to_s
        point = getPlusRatePoint(plus,plus_rate,point)
        if return_cash=="返现"
          #返现 当前消费只计算用户实际支付的金额
          price_F = point
          point = 0
        end
        if chd_price_sum
          #儿童票返利
          chd_point = chd_price_sum*return_rate/100
          logger.error  "儿童票返利值chd_point="+chd_point.to_s
          chd_point = getPlusRatePoint(plus,plus_rate,chd_point)
          if return_cash=="返现"
            chd_price_F = chd_point
            chd_point = 0
          end
        end
        if baby_price_sum
          #婴儿票返利
          baby_point = baby_price_sum*return_rate/100
          logger.error  "婴儿票返利值baby_point="+baby_point.to_s
          baby_point = getPlusRatePoint(plus,plus_rate,baby_point)
          if return_cash=="返现"
            baby_price_F = baby_point
            baby_point = 0
          end
        end
        #today = Time.new.strftime("%Y-%m-%d")
        #计算总价格
        price_sum = 0
        if group && group!=""
          for_length = 0
          price_sum = seat*(hum_price_sum - price_F + fuel_tax + fuel_tax2 + fuel_tax3 + fuel_tax4 + airdrome_tax + airdrome_tax2 + airdrome_tax3 + airdrome_tax4)
        else
          for_length = seat-1
          birthdayArr = birthdayString.split(",")
          humanTypeArr = humanTypeString.split(",")
          for i in 0..for_length
            human_type = humanTypeArr[i]
            if human_type=="婴儿"
              #if birthdayArr[i] && birthdayArr[i].index("-")
              #if birthdayArr[i].to_date>(today.to_date-365)
              price_sum += baby_price_sum - baby_price_F
            elsif human_type=="儿童"
              price_sum += chd_price_sum - chd_price_F
              price_sum += 2*(chd_fuel_tax + chd_fuel_tax2)
            else
              price_sum += hum_price_sum - price_F
              price_sum += fuel_tax + fuel_tax2 + fuel_tax3 + fuel_tax4
              price_sum += airdrome_tax + airdrome_tax2 + airdrome_tax3 + airdrome_tax4
            end
          end
        end
        price_sum = price_sum + insurance_sum #（每张票的票面价+税费）乘以座位数+保险总金额=订单总金额
        logger.error  "订单总金额  price_sum="+price_sum.to_s

        #保存订单
        orderid = saveOrder(uid,cid,owner_id,user.employee_no,pnr,fly_date,fly_time,link_man,link_tel,i_number.to_i,send_address,send_date,send_time,send_request,order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,price_sum,seat,airNo[0,2],web,group,"")
        if orderid
          logger.error "orderid="+orderid.to_s
          #是否是特殊联程价格，特殊联程价格单独处理
          if special_price
            price = special_price
            price2 = 0
            price3 = 0
            price4 = 0

            price_F2 = 0
            point2 = 0
            price_F3 = 0
            point3 = 0
            price_F4 = 0
            point4 = 0
          else
            if special_price1
              price = special_price1
              price2 = 0
              point = price*return_rate/100
              point = getPlusRatePoint(plus,plus_rate,point)
              if return_cash=="返现"
                price_F = point
                point = 0
              end
              price_F2 = 0
              point2 = 0
            else
              point = price*return_rate/100
              point = getPlusRatePoint(plus,plus_rate,point)
              point2 = price2*return_rate/100
              point2 = getPlusRatePoint(plus,plus_rate,point2)
              if return_cash && return_cash=="返现"
                price_F = point
                point = 0
                price_F2 = point2
                point2 = 0
              end
            end
            if special_price2
              price3 = special_price2
              price4 = 0
              point3 = price3*return_rate/100
              point3 = getPlusRatePoint(plus,plus_rate,point3)
              if return_cash=="返现"
                price_F3 = point3
                point3 = 0
              end
              price_F4 = 0
              point4 = 0
            else
              point3 = price3*return_rate/100
              point3 = getPlusRatePoint(plus,plus_rate,point3)
              point4 = price4*return_rate/100
              point4 = getPlusRatePoint(plus,plus_rate,point4)
              if return_cash && return_cash=="返现"
                price_F3 = point3
                point3 = 0
                price_F4 = point4
                point4 = 0
              end
            end
          end
          if chd_price_sum
            #儿童
            chd_point = chd_price*return_rate/100
            chd_point = getPlusRatePoint(plus,plus_rate,chd_point)
            chd_point2 = chd_price2*return_rate/100
            chd_point2 = getPlusRatePoint(plus,plus_rate,chd_point2)
            chd_point3 = chd_price3*return_rate/100
            chd_point3 = getPlusRatePoint(plus,plus_rate,chd_point3)
            chd_point4 = chd_price4*return_rate/100
            chd_point4 = getPlusRatePoint(plus,plus_rate,chd_point4)
            if return_cash && return_cash=="返现"
              chd_price_F = chd_point
              chd_point = 0
              chd_price_F2 = chd_point2
              chd_point2 = 0
              chd_price_F3 = chd_point3
              chd_point3 = 0
              chd_price_F4 = chd_point4
              chd_point4 = 0
            end
          end
          if baby_price_sum
            #婴儿
            baby_point = baby_price*return_rate/100
            baby_point = getPlusRatePoint(plus,plus_rate,baby_point)
            baby_point2 = baby_price2*return_rate/100
            baby_point2 = getPlusRatePoint(plus,plus_rate,baby_point2)
            baby_point3 = baby_price3*return_rate/100
            baby_point3 = getPlusRatePoint(plus,plus_rate,baby_point3)
            baby_point4 = baby_price4*return_rate/100
            baby_point4 = getPlusRatePoint(plus,plus_rate,baby_point4)
            if return_cash && return_cash=="返现"
              baby_price_F = baby_point
              baby_point = 0
              baby_price_F2 = baby_point2
              baby_point2 = 0
              baby_price_F3 = baby_point3
              baby_point3 = 0
              baby_price_F4 = baby_point4
              baby_point4 = 0
            end
          end
          go = true
          nameArr = nameString.split(",")
          humanTypeArr = humanTypeString.split(",")
          cardArr = cardString.split(",")
          birthdayArr = birthdayString.split(",")
          insuranceArr = insuranceString.split(",")
          for i in 0..seat-1
            human_type = ""
            id_card = ""
            birthday = ""
            insurance_number = 0

            passenger_name = nameArr[i]
            human_type = humanTypeArr[i] if humanTypeArr[i]
            id_card = cardArr[i] if cardArr[i]
            birthday = birthdayArr[i] if birthdayArr[i]
            insurance_number = insuranceArr[i].to_i if insuranceArr[i]

            logger.error "乘客="+passenger_name
            logger.error "类型="+human_type
            logger.error "证件号="+id_card
            logger.error "出生日期="+birthday
            logger.error "保险份数="+insurance_number.to_s

            if human_type=="婴儿"
              #if birthday.to_date>(today.to_date-365)
              t_price = baby_price
              t_price_F = baby_price_F
              t_point = baby_point
              t_price2 = baby_price2
              t_price_F2 = baby_price_F2
              t_point2 = baby_point2
              t_price3 = baby_price3
              t_price_F3 = baby_price_F3
              t_point3 = baby_point3
              t_price4 = baby_price4
              t_price_F4 = baby_price_F4
              t_point4 = baby_point4
            elsif human_type=="儿童"
              t_price = chd_price
              t_price_F = chd_price_F
              t_point = chd_point
              t_price2 = chd_price2
              t_price_F2 = chd_price_F2
              t_point2 = chd_point2
              t_price3 = chd_price3
              t_price_F3 = chd_price_F3
              t_point3 = chd_point3
              t_price4 = chd_price4
              t_price_F4 = chd_price_F4
              t_point4 = chd_point4
            else
              t_price = price
              t_price_F = price_F
              t_point = point
              t_price2 = price2
              t_price_F2 = price_F2
              t_point2 = point2
              t_price3 = price3
              t_price_F3 = price_F3
              t_point3 = point3
              t_price4 = price4
              t_price_F4 = price_F4
              t_point4 = point4
            end
            if saveTicket(cid,pnr,orderid,"",airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,t_price,t_price_F,t_point,passenger_name,human_type,id_card,birthday,insurance_number,status,trip_type)
              if saveTicket(cid,pnr,orderid,"",airNo2,fromto2,fly_date2,fly_time2,arr_time2,plane_type2,position2,status_type2,t_price2,t_price_F2,t_point2,passenger_name,human_type,id_card,birthday,0,status,trip_type)
                if saveTicket(cid,pnr,orderid,"",airNo3,fromto3,fly_date3,fly_time3,arr_time3,plane_type3,position3,status_type3,t_price3,t_price_F3,t_point3,passenger_name,human_type,id_card,birthday,0,status,trip_type)
                  if !saveTicket(cid,pnr,orderid,"",airNo4,fromto4,fly_date4,fly_time4,arr_time4,plane_type4,position4,status_type4,t_price4,t_price_F4,t_point4,passenger_name,human_type,id_card,birthday,0,status,trip_type)
                    logger.error "-----保存乘客"+passenger_name+"的"+airNo4+"票记录失败-----"
                    go = false
                    break
                  end
                else
                  logger.error "-----保存乘客"+passenger_name+"的"+airNo3+"票记录失败-----"
                  go = false
                  break
                end
              else
                logger.error "-----保存乘客"+passenger_name+"的"+airNo2+"票记录失败-----"
                go = false
                break
              end
            else
              logger.error "-----保存乘客"+passenger_name+"的"+airNo+"票记录失败-----"
              go = false
              break
            end
          end
          logger.error go
          logger.error "=========== ending ============="
          if go
            return true
          end
        end
      end
      logger.error  "CommonHelper saveMulOrderTicket3 结束"
      return false
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","saveMulOrderTicket3",e,"error")
      return false
    end
  end

  #婴儿
  def self.saveBabyTicket(id,name,birthday,insurance_number)
    begin
      h_ticket = Ticket.find_by_id(id) if id
      return false if id==nil || h_ticket==nil
      ticket = Ticket.new
      h_ticket.attributes.each do |attr, value|
        eval("ticket.#{attr} = h_ticket.#{attr}")
      end

      price_F = 0
      transaction do #事务
        insurance_sum = Constants::DEFAULT_INSURANCE_PRICE*insurance_number.to_i
        #如果这个婴儿没有常旅客信息，则添加常旅客信息，只有婴儿姓名，没有身份证号和电话
        passenger = Customer.find(:first,:conditions => ["name=? and (card is null or card='')",name])
        if passenger==nil
          passenger = Customer.new
          passenger.name = name
          passenger.birthday = birthday if birthday
          passenger.card = ""
          passenger.phone = ""
          passenger.customer_type_id = 1 #1表示为常旅客
          passenger.save
        end
        #婴儿票是全价的10% 没有燃油 机建
        price = getBabyPrice(ticket.air_no[0,2],ticket.fromto)
        #增加客户累计积分和累计消费
        order = ticket.order
        customer = order.customer
        #如果有客户记录，则添加客户的积分、累计消费等数据
        customer_type = customer.customer_type
        return_cash = customer_type.return_cash
        logger.error  "返利类型return_cash="+return_cash
        return_rate = customer_type.return_rate
        logger.error  "返利比率return_rate="+return_rate.to_s
        point = price*return_rate/100
        logger.error  "返利值point="+point.to_s
        plus = customer_type.plus
        plus_rate = customer_type.plus_rate
        point = getPlusRatePoint(plus,plus_rate,point)
        if return_cash=="返现"
          #返现 当前消费只计算用户实际支付的金额
          price_F = point
          point = 0
        end

        #婴儿是否需要增加乘客人数
        #order.seat += 1
        #增加订单总金额
        order.price_sum += price - price_F + insurance_sum
        order.save

        #保存婴儿票记录
        ticket.id = nil
        ticket.passenger_id = passenger.id
        ticket.ticket_type = "婴儿"
        ticket.insurance_number = insurance_number.to_i
        ticket.father_id = id.to_i

        ticket.price = price
        ticket.airdrome_tax = 0
        ticket.fuel_tax = 0
        ticket.price_F = price_F
        ticket.point = point
        ticket.insurance_F = 0
        ticket.other = 0
        ticket.total_price = price + insurance_sum
        if ticket.save
          return true
        end
      end
      return false
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","saveBabyTicket",e,"error")
      return false
    end
  end

  #出票 获取票号
  def self.outTicketByOrder(oid,uid,eterm_name,eterm_pswd)
    begin
      logger.error "=============CommonHelper outTicketByOrder==============="
      result = "提取票号失败"
      order = Order.find_by_id(oid)
      if order
        pnr = order.pnr
        cmd = "rt"+pnr
        res = SocketHelper.callSocket(cmd,eterm_name,eterm_pswd)
        if res.index("timeout")
          result = "连接服务器超时!"
        elsif res.index("socket is null") || res==""
          result = "访问服务器失败!"
        elsif res.index("NO PNR")
          result = "该PNR不存在"
        elsif res.index("*THIS PNR WAS ENTIRELY CANCELLED*")
          result = "该PNR已经被取消"
        else
          res = res.gsub(/\r/,"")
          res = res.gsub(/\n/,"<br>")
          res1 = res.gsub(/ {1,}/," ")

          transaction do #事务
            if res1.index("**ELECTRONIC TICKET PNR**")
              #bsp出票
              res2 = res1
              while res2.index("SSR TKNE")
                res2 = res2[res2.index("SSR TKNE")..-1]
                res3 = res2[0,res2.index("<br>")].gsub(/ {1,}$/,"")
                #logger.error "---行内容="+res3+"---"
                if res3.rindex("/P")
                  no = res3[res3.rindex("/P")+2..-1].to_i
                end
                if no==nil || no==0
                  no = "1"
                end
                ticket_no = res3[res3.rindex(" ")+1..res3.index("/")-1]
                if ticket_no.index("-")==nil
                  ticket_no = ticket_no[0,3]+"-"+ticket_no[3..12]
                end
                res4 = res1[res1.index(no+".")+2..-1]
                name = res4[0,res4.index(" ")]
                name = name[0,name.index("CHD(")] if name.index("CHD(")
                #订单中票号跟着乘客 联程或往返 一个乘客的多个ticket记录中票号相同
                Ticket.update_all("status='"+Constants::TICKET_STATUS_YCP+"',ticket_no='"+ticket_no+"'",["order_id=? and passenger_id in(select id from customers where name=?)",oid,name])

                res2 = res2[res2.index("<br>")+4..-1]
              end
              result = "提取成功"
            elsif res1.index("OSI")
              #网站出票
              res2 = res1
              while res2.index("OSI")
                res2 = res2[res2.index("OSI")..-1]
                res3 = res2[0,res2.index("<br>")].gsub(/ {1,}$/,"")
                #logger.error "---行内容="+res3+"---"
                if res3.rindex("/P")
                  no = res3[res3.rindex("/P")+2..-1]
                  ticket_no = res3[res3.index("/")+1..res3.rindex("/P")-1]
                else
                  no = "1"
                  ticket_no = res3[res3.index("/")+1..-1]
                end
                if ticket_no.index("-")==nil
                  ticket_no = ticket_no[0,3]+"-"+ticket_no[3..12]
                end
                res4 = res1[res1.index(no+".")+2..-1]
                name = res4[0,res4.index(" ")]
                name = name[0,name.index("CHD(")] if name.index("CHD(")

                Ticket.update_all("status='"+Constants::TICKET_STATUS_YCP+"',ticket_no='"+ticket_no+"'",["order_id=? and passenger_id in(select id from customers where name=?)",oid,name])

                res2 = res2[res2.index("<br>")+4..-1]
              end
              result = "提取成功"
            elsif res1.index(".T/")
              #CZ 手工输入的票号
              res2 = res1
              res2 = res2[res2.index(".T/")+3..-1]
              res3 = res2[0,res2.index("<br>")].gsub(/ {1,}$/,"")
              #logger.error "---行内容="+res3+"---"
              if res3.index("/OK")
                res3 = res3[0,res3.index("/OK")]
                if res3.length==14
                  ticket_no = res3
                else
                  no = 1
                  while(res3.index("-"))
                    if res3.index("-")==3
                      ticket_no = res3[0,14]

                      res4 = res1[res1.index(no.to_s+".")+2..-1]
                      name = res4[0,res4.index(" ")]
                      name = name[0,name.index("CHD(")] if name.index("CHD(")

                      Ticket.update_all("status='"+Constants::TICKET_STATUS_YCP+"',ticket_no='"+ticket_no+"'",["order_id=? and passenger_id in(select id from customers where name=?)",oid,name])

                      res3 = res3[4..-1]
                      if res3.index("-")
                        res3 = res3[res3.index("-")+1..-1]
                      else
                        break
                      end
                      no += 1
                    else
                      res3 = res3[res3.index("-")+1..-1]
                    end
                  end
                end
              end
              result = "提取成功"
            else
              result = "没有发现票号信息，该pnr不是BSP出票或者没有OSI信息"
            end
            if result == "提取成功"
              #更新出票信息
              order.ticket_outer_id = uid.to_i
              order.ticket_out_date = Time.new
              order.status = Constants::ORDER_STATUS_YCP
              order.save
            end
          end
        end
      end
      return result
    rescue Exception => e
      logger.error("CommonHelper outTicketByOrder e="+e.message)
      infoLogger(nil,nil,"Common_Helper","outTicketByOrder",e,"error")
    end
  end

  #修改航段
  def self.modTicketAirline(id,trip_type,option,
      airNo,fromto,fly_date,fly_time,arr_time,position,plane_type,price,
      airNo2,fromto2,fly_date2,fly_time2,arr_time2,position2,plane_type2,price2,
      airNo3,fromto3,fly_date3,fly_time3,arr_time3,position3,plane_type3,price3,
      airNo4,fromto4,fly_date4,fly_time4,arr_time4,position4,plane_type4,price4)

    begin
      logger.error "========== CommonHelper modTicketAirline ============="
      result = false
      price = price.to_i
      price_F = 0
      point = 0
      order = Order.find_by_id(id)
      if order
        airdrome_tax = getPlaneTax(plane_type)
        fuel_tax = getFuelTax(fromto)
        airdrome_tax2 = getPlaneTax(plane_type2) if plane_type2
        fuel_tax2 = getFuelTax(fromto2) if fromto2
        airdrome_tax3 = getPlaneTax(plane_type3) if plane_type3
        fuel_tax3 = getFuelTax(fromto3) if fromto3
        airdrome_tax4 = getPlaneTax(plane_type4) if plane_type4
        fuel_tax4 = getFuelTax(fromto4) if fromto4

        baby_price = getBabyPrice(airNo[0,2],fromto)
        baby_price2 = getBabyPrice(airNo2[0,2],fromto2) if airNo2 && fromto2
        baby_price3 = getBabyPrice(airNo3[0,2],fromto3) if airNo3 && fromto3
        baby_price4 = getBabyPrice(airNo4[0,2],fromto4) if airNo4 && fromto4
        chd_price = getChdPrice(airNo[0,2],fromto)
        chd_price2 = getChdPrice(airNo2[0,2],fromto2) if airNo2 && fromto2
        chd_price3 = getChdPrice(airNo3[0,2],fromto3) if airNo3 && fromto3
        chd_price4 = getChdPrice(airNo4[0,2],fromto4) if airNo4 && fromto4

        #获取积分返现比率
        customer = order.customer
        customer_type = customer.customer_type
        return_cash = customer_type.return_cash
        logger.error  "return_cash="+return_cash
        return_rate = customer_type.return_rate
        logger.error  "return_rate="+return_rate.to_s
        plus = customer_type.plus
        plus_rate = customer_type.plus_rate

        passenger_id_str = ","
        transaction do #事务
          price_sum = 0
          #tickets = order.tickets
          sql = " and status <> '"+Constants::TICKET_STATUS_YQX+"' and status <> '"+Constants::TICKET_STATUS_YTP+"' and status <> '"+Constants::TICKET_STATUS_YZF+"'"
          tickets = Ticket.find(:all,:conditions=>["order_id=? and is_locked<>1 "+sql,order.id])
          for ticket in tickets
            passenger_id = ticket.passenger_id.to_s
            logger.error "乘客id="+passenger_id
            if passenger_id_str.index(","+passenger_id+",")
              #已经处理过这个乘客了
            else
              passenger_id_str << passenger_id+","
              #复制原记录，保存乘客信息
              new_ticket = Ticket.new
              ticket.attributes.each do |attr, value|
                eval("new_ticket.#{attr} = ticket.#{attr}") if attr!="id" && attr!="ticket_no"
              end

              logger.error "航班号="+airNo
              #重新对航班相关字段赋值
              new_ticket.air_no = airNo
              new_ticket.fromto = fromto
              new_ticket.fly_date = fly_date
              new_ticket.fly_time = fly_time
              new_ticket.arr_time = arr_time
              new_ticket.position = position
              new_ticket.plane_type = plane_type
              if new_ticket.ticket_type=="儿童"
                new_ticket.airdrome_tax = 0
                new_ticket.fuel_tax = getRightPrice(fuel_tax/2)
                new_ticket.price = chd_price
              elsif new_ticket.ticket_type=="婴儿"
                new_ticket.airdrome_tax = 0
                new_ticket.fuel_tax = 0
                new_ticket.price = baby_price
              else
                new_ticket.airdrome_tax = airdrome_tax
                new_ticket.fuel_tax = fuel_tax
                new_ticket.price = price
              end
              #计算积分返利
              price_F = 0
              point = 0
              if return_rate && return_rate>0
                point = new_ticket.price*return_rate/100
                point = getPlusRatePoint(plus,plus_rate,point)
                logger.error  "point="+point.to_s
                if return_cash=="返现"
                  price_F = point
                  point = 0
                end
              end
              new_ticket.total_price = new_ticket.price - price_F + new_ticket.airdrome_tax + new_ticket.fuel_tax + new_ticket.insurance_number*Constants::DEFAULT_INSURANCE_PRICE
              new_ticket.price_F = price_F
              new_ticket.point = point
              new_ticket.trip_type = trip_type
              #获取政策
              policy = getPolicy(nil,airNo,fromto,fly_date,position,trip_type)
              if policy
                new_ticket.rake_off = policy.rake_off
                new_ticket.policy_id = policy.id
              else
                new_ticket.rake_off = Constants::DEFAULT_RAKE_OFF
                new_ticket.policy_id = nil
              end
              new_ticket.save
              logger.error "id="+new_ticket.id.to_s
              price_sum += new_ticket.total_price
              logger.error  "price_sum="+price_sum.to_s
              if airNo2 && airNo2!=""
                logger.error "航班号="+airNo2
                #复制原记录，保存乘客信息
                new_ticket = Ticket.new
                ticket.attributes.each do |attr, value|
                  eval("new_ticket.#{attr} = ticket.#{attr}") if attr!="id" && attr!="ticket_no"
                end
                #重新对航班相关字段赋值
                new_ticket.air_no = airNo2
                new_ticket.fromto = fromto2
                new_ticket.fly_date = fly_date2
                new_ticket.fly_time = fly_time2
                new_ticket.arr_time = arr_time2
                new_ticket.position = position2
                new_ticket.plane_type = plane_type2
                if new_ticket.ticket_type=="儿童"
                  new_ticket.airdrome_tax = 0
                  new_ticket.fuel_tax = getRightPrice(fuel_tax2/2)
                  new_ticket.price = chd_price2
                elsif new_ticket.ticket_type=="婴儿"
                  new_ticket.airdrome_tax = 0
                  new_ticket.fuel_tax = 0
                  new_ticket.price = baby_price2
                else
                  new_ticket.airdrome_tax = airdrome_tax2
                  new_ticket.fuel_tax = fuel_tax2
                  new_ticket.price = price2
                end
                #计算积分返利
                price_F = 0
                point = 0
                if return_rate && return_rate>0
                  point = new_ticket.price*return_rate/100
                  point = getPlusRatePoint(plus,plus_rate,point)
                  logger.error  "point="+point.to_s
                  if return_cash=="返现"
                    price_F = point
                    point = 0
                  end
                end
                new_ticket.total_price = new_ticket.price - price_F + new_ticket.airdrome_tax + new_ticket.fuel_tax + new_ticket.insurance_number*Constants::DEFAULT_INSURANCE_PRICE
                new_ticket.price_F = price_F
                new_ticket.point = point
                new_ticket.trip_type = trip_type
                #获取政策
                policy = getPolicy(nil,airNo2,fromto2,fly_date2,position2,trip_type)
                if policy
                  new_ticket.rake_off = policy.rake_off
                  new_ticket.policy_id = policy.id
                else
                  new_ticket.rake_off = Constants::DEFAULT_RAKE_OFF
                  new_ticket.policy_id = nil
                end
                new_ticket.save
                logger.error "id="+new_ticket.id.to_s
                price_sum += new_ticket.total_price
                logger.error  "price_sum="+price_sum.to_s
              end
              if airNo3 && airNo3!=""
                logger.error "航班号="+airNo3
                #复制原记录，保存乘客信息
                new_ticket = Ticket.new
                ticket.attributes.each do |attr, value|
                  eval("new_ticket.#{attr} = ticket.#{attr}") if attr!="id" && attr!="ticket_no"
                end
                #重新对航班相关字段赋值
                new_ticket.air_no = airNo3
                new_ticket.fromto = fromto3
                new_ticket.fly_date = fly_date3
                new_ticket.fly_time = fly_time3
                new_ticket.arr_time = arr_time3
                new_ticket.position = position3
                new_ticket.plane_type = plane_type3
                if new_ticket.ticket_type=="儿童"
                  new_ticket.airdrome_tax = 0
                  new_ticket.fuel_tax = getRightPrice(fuel_tax3/2)
                  new_ticket.price = chd_price3
                elsif new_ticket.ticket_type=="婴儿"
                  new_ticket.airdrome_tax = 0
                  new_ticket.fuel_tax = 0
                  new_ticket.price = baby_price3
                else
                  new_ticket.airdrome_tax = airdrome_tax3
                  new_ticket.fuel_tax = fuel_tax3
                  new_ticket.price = price3
                end
                #计算积分返利
                price_F = 0
                point = 0
                if return_rate && return_rate>0
                  point = new_ticket.price*return_rate/100
                  point = getPlusRatePoint(plus,plus_rate,point)
                  logger.error  "point="+point.to_s
                  if return_cash=="返现"
                    price_F = point
                    point = 0
                  end
                end
                new_ticket.total_price = new_ticket.price - price_F + new_ticket.airdrome_tax + new_ticket.fuel_tax + new_ticket.insurance_number*Constants::DEFAULT_INSURANCE_PRICE
                new_ticket.price_F = price_F
                new_ticket.point = point
                new_ticket.trip_type = trip_type
                #获取政策
                policy = getPolicy(nil,airNo3,fromto3,fly_date3,position3,trip_type)
                if policy
                  new_ticket.rake_off = policy.rake_off
                  new_ticket.policy_id = policy.id
                else
                  new_ticket.rake_off = Constants::DEFAULT_RAKE_OFF
                  new_ticket.policy_id = nil
                end
                new_ticket.save
                logger.error "id="+new_ticket.id.to_s
                price_sum += new_ticket.total_price
                logger.error  "price_sum="+price_sum.to_s
              end
              if airNo4 && airNo4!=""
                logger.error "航班号="+airNo4
                #复制原记录，保存乘客信息
                new_ticket = Ticket.new
                ticket.attributes.each do |attr, value|
                  eval("new_ticket.#{attr} = ticket.#{attr}") if attr!="id" && attr!="ticket_no"
                end
                #重新对航班相关字段赋值
                new_ticket.air_no = airNo4
                new_ticket.fromto = fromto4
                new_ticket.fly_date = fly_date4
                new_ticket.fly_time = fly_time4
                new_ticket.arr_time = arr_time4
                new_ticket.position = position4
                new_ticket.plane_type = plane_type4
                if new_ticket.ticket_type=="儿童"
                  new_ticket.airdrome_tax = 0
                  new_ticket.fuel_tax = getRightPrice(fuel_tax4/2)
                  new_ticket.price = chd_price4
                elsif new_ticket.ticket_type=="婴儿"
                  new_ticket.airdrome_tax = 0
                  new_ticket.fuel_tax = 0
                  new_ticket.price = baby_price4
                else
                  new_ticket.airdrome_tax = airdrome_tax4
                  new_ticket.fuel_tax = fuel_tax4
                  new_ticket.price = price4
                end
                #计算积分返利
                price_F = 0
                point = 0
                if return_rate && return_rate>0
                  point = new_ticket.price*return_rate/100
                  point = getPlusRatePoint(plus,plus_rate,point)
                  logger.error  "point="+point.to_s
                  if return_cash=="返现"
                    price_F = point
                    point = 0
                  end
                end
                new_ticket.total_price = new_ticket.price - price_F + new_ticket.airdrome_tax + new_ticket.fuel_tax + new_ticket.insurance_number*Constants::DEFAULT_INSURANCE_PRICE
                new_ticket.price_F = price_F
                new_ticket.point = point
                new_ticket.trip_type = trip_type
                #获取政策
                policy = getPolicy(nil,airNo4,fromto4,fly_date4,position4,trip_type)
                if policy
                  new_ticket.rake_off = policy.rake_off
                  new_ticket.policy_id = policy.id
                else
                  new_ticket.rake_off = Constants::DEFAULT_RAKE_OFF
                  new_ticket.policy_id = nil
                end
                new_ticket.save
                logger.error "id="+new_ticket.id.to_s
                price_sum += new_ticket.total_price
                logger.error  "price_sum="+price_sum.to_s
              end
            end
            if option=="mod"
              logger.error "----- del old ticket -----"+ticket.id.to_s
              ticket.destroy
            end
          end
          #更新订单总金额
          if option=="mod"
            order.price_sum = price_sum
          else
            order.price_sum += price_sum
          end
          if order.save
            result = true
          end
        end
      end
      return result
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","modTicketAirline",e,"error")
      return false
    end
  end

  def self.getRtPnrResult(pnr,eterm_name,eterm_pswd)
    begin
      res = ""
      cmd = "rt"+pnr
      rubySocket = SocketHelper.getSocket(eterm_name,eterm_pswd)
      if rubySocket
        res = SocketHelper.getCR(rubySocket,cmd,true)
        logger.error "-----rt#{pnr}结果"
        logger.error res
        if res.index(pnr)
          if (res.index("0.") && res.index(" NM"))
            #group = "团体订单"
            cmd = "rtn"
            res = SocketHelper.getCR(rubySocket,cmd,true)
            logger.error "-----团体票rtn结果"
            logger.error res
          end
          #第一次翻页
          res2 = SocketHelper.getCR(rubySocket,"pn",true)
          logger.error "-----pn翻页结果"
          logger.error res2
          if res2.index(" "+pnr)==nil
            res << "\r\n"+res2
            #第二次翻页
            res3 = SocketHelper.getCR(rubySocket,"pn",true)
            logger.error "-----第二次pn翻页结果"
            logger.error res3
            res << "\r\n"+res3 if res3.index(" "+pnr)==nil && res3!=res2
          end
        end
        logger.error "-----提取pnr结果"
        logger.error res
        res = res.strip
        if rubySocket
          rubySocket.close
          rubySocket=nil
        end
      else
        res = "连接放大器失败,或用户已被占用!"
      end
      if res==""
        res = "没有返回信息!"
      elsif res.index("timeout")
        res = "连接服务器超时!"
      elsif res.index("socket is null")
        res = "访问服务器失败!"
      end
      return res
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getRtPnrResult",e,"error")
      rubySocket.close if rubySocket
      return ""
    end
  end
  
  #提取pnr形成订单
  def self.saveOrderByPnr(pnr,type,uid,eterm_name,eterm_pswd)
    begin
      web = ""
      group = ""
      inter = ""
      result = "提取失败"
      if pnr && uid
        logger.error ">>>>>>> saveOrderByPnr >>>>>>>>"
        web = "web订单" if type && type=="web"
        inter = "国际订单" if type && type=="gj"
        pnr = pnr.upcase #转大写
        user = User.find_by_id(uid)

        res = getRtPnrResult(pnr,eterm_name,eterm_pswd)
        if res.index("ENTIRELY CANCELLED")
          result = "#{pnr}已经取消"
        elsif res.index(pnr)
          if (res.index("0.") && res.index(" NM"))
            group = "团体订单"
          end
          res = res.gsub(/\r/,"")
          res = res.gsub(/\n/,"<br>")
          res = res.gsub(/ {2,}/," ")
          res = res.gsub(/ \+{1,}/,"")
          res = res.gsub(/ \-{1,}/,"<br>")  #替换+-号为换行
          res = res.strip
          logger.error "-----res="
          logger.error res

          pass_nameArr = Array.new
          cardArr = Array.new
          baby_nameArr = Array.new
          baby_dateArr = Array.new

          air_noArr = Array.new
          positionArr = Array.new
          fromtoArr = Array.new
          fly_dateArr = Array.new
          arr_timeArr = Array.new
          fly_timeArr = Array.new
          status_typeArr = Array.new
          priceArr = Array.new
          ticketNoArr = Array.new
          
          seat = 1 #座位数 婴儿不占座
          res1 = res[0,res.index(". ")+2]
          flght_no = res1[res1.rindex("<br>")+4..-1].to_i
          logger.error "flght_no="+flght_no.to_s
          seat = flght_no-1
          res2 = res[res1.rindex("<br>")+4..-1]
    
          logger.error "-----乘客姓名res1="
          logger.error res1
          for i in 1..flght_no-1
            logger.error "-----第"+i.to_s+"位乘客"
            if i>9
              startNum = res1.index(i.to_s+".")+3
            else
              startNum = res1.index(i.to_s+".")+2
            end
            endNum = res1.index((i+1).to_s+".")-1
            res3 = res1[startNum..endNum]
            logger.error "---"+res3+"---"
            res3 = res3[0,res3.index(" ")] if res3.index(" ")
            res3 = res3.gsub(/<br>/,"").strip
            logger.error "---"+res3+"---"
            eval("pass_nameArr[#{i-1}] = res3")
          end
    
          logger.error "-----res2="
          logger.error res2
          toYear = Time.new.strftime("%Y").to_s
          air_no_num = 0
          while(res2.index("<br>"))
            res3 = res2[0,res2.index("<br>")].strip
            logger.error  "-----行结果="+res3
            if res3.index(". ") && res3.rindex(" ")>30
              logger.error "#航班信息"
              num = air_no_num
              res4 = res3[res3.index(" ")+1..-1]
              air_no = res4[0,res4.index(" ")]
              air_no = air_no[1..-1] if air_no.index("*")
              logger.error air_no
              eval("air_noArr[#{num}] = air_no")

              res4 = res4[res4.index(" ")+1..-1]
              position = res4[0,res4.index(" ")]
              logger.error position
              eval("positionArr[#{num}] = position")

              res4 = res4[res4.index(" ")+1..-1]
              res5 = res4[0,7]
              #TH28AUG 转化成2008-09-09的形式
              m = getMonthByStr(res5[4,3])
              fly_date = toYear+"-"+m+"-"+res5[2,2]
              logger.error fly_date
              eval("fly_dateArr[#{num}] = fly_date")

              if res4.index(" ")>9
                #日期和城市对中间没有空格
                if res4[7,2].to_i>0
                  #乘机日期中带有年份
                  res4 = res4[9..-1]
                else
                  res4 = res4[7..-1]
                end
              else
                res4 = res4[res4.index(" ")+1..-1]
              end
              if res4.index(" ")>6
                #城市对和状态中间不是空格
                fromto = res4[0,6]
                logger.error fromto
                status_type = res4[7,2]
                logger.error status_type
                seat = res5[9..-1].to_i
                logger.error seat
              else
                fromto = res4[0,res4.index(" ")]
                logger.error fromto
                res4 = res4[res4.index(" ")+1..-1]
                res5 = res4[0,res4.index(" ")]
                status_type = res5[0,2]
                logger.error status_type
                seat = res5[2..-1].to_i
                logger.error seat
              end
              eval("fromtoArr[#{num}] = fromto")
              eval("status_typeArr[#{num}] = status_type")

              res4 = res4[res4.index(" ")+1..-1]
              fly_time = res4[0,res4.index(" ")]
              fly_time = fly_time[0,2]+":"+fly_time[2,2]
              logger.error fly_time
              eval("fly_timeArr[#{num}] = fly_time")

              res4 = res4[res4.index(" ")+1..-1]
              arr_time = res4[0,res4.index(" ")]
              arr_time = arr_time[0,2]+":"+arr_time[2,2]
              logger.error arr_time
              eval("arr_timeArr[#{num}] = arr_time")

              positionPrice = PositionPrice.find(:first,:conditions=>["fromto=? and position=?",fromto,position])
              if positionPrice && positionPrice.price
                price = positionPrice.price
              else
                price = 0
              end
              logger.error price
              eval("priceArr[#{num}] = price")

              air_no_num += 1
            elsif res3.index(".TL")
              logger.error "#时限"
              res4 = res3[res3.index("/")+1..-1]
              tktl_time = res4[0,res4.index("/")]
              #tktl_time = tktl_time[0,2]+":"+tktl_time[2,2]
              logger.error tktl_time
              res4 = res4[res4.index("/")+1..-1]
              res5 = res4[0,res4.index("/")]
              logger.error res5
              #06AUG 转化为2008-09-09格式
              m = getMonthByStr(res5[2,3])
              tktl_date = toYear+"-"+m+"-"+res5[0,2]
              logger.error tktl_date
            elsif res3.index("SSR FOID")
              logger.error "#证件号"
              if res3.index("NI")
                res4 = res3[res3.index("NI")+2..-1]
              elsif res3.index("PPG")
                res4 = res3[res3.index("PPG")+3..-1]
              else
                res4 = ""
              end
              if res4.index("/P")
                res5 = res4[0,res4.index("/")]
                num = res4[res4.index("/P")+2..-1].to_i
                logger.error num
                logger.error res5
                num -= 1
                eval("cardArr[#{num}] = res5")
              end
            elsif res3.index("TN/")
              logger.error "#票号"
              res4 = res3[res3.index("TN/")+3..-1]
              if res4.index("/P")
                num = res4[res4.index("/P")+2..-1].to_i
                res5 = res4[0,res4.index("/P")]
                logger.error num
                logger.error res5
                num -= 1
                eval("ticketNoArr[#{num}] = res5")
              end
            elsif res3.index("SSR INFT")
              logger.error "#婴儿出生年月日"
              res4 = res3[res3.rindex(" ")+1..-1]
              if res4.index("/P")
                res5 = res4[0,res4.index("/")]
                logger.error res5
                #12FEB08 转化成2008-09-09的形式
                m = getMonthByStr(res5[2,3])
                baby_date = "20"+res5[5,2]+"-"+m+"-"+res5[0,2]
                logger.error baby_date
                num = res4[res4.index("/P")+2..-1].to_i
                logger.error num
                num -= 1
                eval("baby_dateArr[#{num}] = baby_date")
              end
            elsif res3.index("XN/IN/")
              logger.error "#婴儿姓名"
              res4 = res3[res3.index("XN/IN/")+6..-1]
              res5 = res4[0,res4.index("INF")]
              logger.error res5
              if res4.index("/P")
                num = res4[res4.index("/P")+2..-1].to_i
                logger.error num
                num -= 1
                eval("baby_nameArr[#{num}] = res5")
              else
                baby_nameArr[0] = res5
              end
            end
            res2 = res2[res2.index("<br>")+4..-1]
          end
    
          logger.error ">>>>>>>>>>>>>>>>>>"
          logger.error pass_nameArr
          logger.error cardArr
          logger.error baby_nameArr
          logger.error baby_dateArr
          logger.error air_noArr
          logger.error positionArr
          logger.error fromtoArr
          logger.error fly_dateArr
          logger.error arr_timeArr
          logger.error fly_timeArr
          logger.error status_typeArr
          logger.error ticketNoArr
          
          transaction do #事务
            insurance_number = 0
            trip_type = ""
            if fromtoArr.length>1
              fromto0 = fromtoArr[0]
              fromto1 = fromtoArr[1]
              if fromto0 == fromto1[3,3]+fromto1[0,3]
                trip_type = "往返"
              else
                trip_type = "联程"
              end
            end
            logger.error trip_type

            if air_noArr.length>0
              go = true
              fly_date = fly_dateArr[0]
              fly_time = fly_timeArr[0]
              link_man = ""
              link_tel = ""
              send_address = ""
              send_time = ""
              send_request = ""
              order_request = ""
              jj_address = ""
              jj_request = ""
              tktl_time = "" if tktl_time==nil
              tktl_date = nil if tktl_date==nil
              price_sum = 0
              orderid = saveOrder(user.id,1,user.id,user.employee_no,pnr,fly_date,fly_time,link_man,link_tel,insurance_number,send_address,nil,send_time,send_request,order_request,jj_address,nil,jj_request,tktl_date,tktl_time,nil,nil,price_sum,pass_nameArr.length,air_no[0,2],web,group,inter)
              if orderid
                logger.error "===订单id="+orderid.to_s
                ticketidArr = Array.new
                logger.error "乘客个数="+pass_nameArr.length.to_s
                logger.error "======循环乘客======"
                0.upto(pass_nameArr.length-1) do |i|
                  logger.error "第"+i.to_s+"个乘客="+pass_nameArr[i]
                  passenger_name = pass_nameArr[i]
                  human_type = ""
                  if cardArr[i]
                    logger.error "证件="+cardArr[i]
                    id_card = cardArr[i]
                  else
                    id_card = ""
                  end
                  #TODO 获取票号
                  status = Constants::TICKET_STATUS_WQR
                  logger.error "===循环航班==="
                  0.upto(air_noArr.length-1) do |j|
                    if air_noArr[j]
                      airNo = air_noArr[j]
                      logger.error "第"+j.to_s+"个航班="+airNo
                    
                      fromto = ""
                      fly_date = ""
                      fly_time = ""
                      arr_time = ""
                      position = ""
                      status_type = "HK"
                      plane_type = ""
                      ticket_no = ""
                      
                      fromto = fromtoArr[j] if fromtoArr[j]
                      fly_date = fly_dateArr[j] if fly_dateArr[j]
                      fly_time = fly_timeArr[j] if fly_timeArr[j]
                      arr_time = arr_timeArr[j] if arr_timeArr[j]
                      position = positionArr[j] if positionArr[j]
                      status_type = status_typeArr[j] if status_typeArr[j]
                      ticket_no = ticketNoArr[j] if ticketNoArr[j]
                      price = 0
                      price = priceArr[j].to_i if priceArr[j]
                      price_F = 0
                      point = 0

                      tid = saveTicket(1,pnr,orderid,ticket_no,airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price,price_F,point,passenger_name,human_type,id_card,"",insurance_number,status,trip_type)
                      if tid
                        ticketidArr.push(tid)
                        #logger.error "===票id数组==="
                        #logger.error ticketidArr
                      else
                        go = false
                        result = "保存航班信息失败,航班号是#{airNo},乘客是#{passenger_name}"
                        #如果失败，删除记录
                        delOrderTicket(orderid)
                        break
                      end
                    end
                  end #循环航班
                  logger.error "===循环航班 end==="
                end #循环乘客
                logger.error "======循环乘客 end======"
                #循环婴儿
                logger.error "==婴儿个数=="
                logger.error baby_nameArr.length
                for i in 0..baby_nameArr.length-1
                  if baby_nameArr[i]
                    baby_name = baby_nameArr[i]
                    baby_date = baby_dateArr[i]
                    logger.error "第"+i.to_s+"个大人所带的婴儿="+baby_name
                    logger.error "出生日期="+baby_date
                    0.upto(air_noArr.length-1) do |j|
                      ii = i*air_noArr.length + j
                      logger.error ii
                      logger.error ticketidArr[ii]
                      if !saveBabyTicket(ticketidArr[ii],baby_name,baby_date,0)
                        go = false
                        result = "保存婴儿票失败,婴儿是#{baby_name}"
                        #如果失败，删除记录
                        delOrderTicket(orderid)
                      end
                    end
                  end
                end
                logger.error "==循环婴儿 end=="
                if go
                  #更新订单总金额
                  tickets = Ticket.find_by_sql("select sum(total_price) as price_sum from tickets where order_id="+orderid.to_s+" and is_locked<>1")
                  price_sum = tickets[0].price_sum
                  logger.error "订单总金额="+price_sum.to_s
                  Order.update_all("price_sum="+price_sum.to_s,["id=?",orderid])
                  
                  result = orderid.to_s
                end
              else
                result = "保存订单信息失败,请检查pnr中信息是否正确"
              end
            else
              result = "该pnr中没有航班信息"
            end
          end #结束事务
        else
          result = res
        end
      end
      return result
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","saveOrderByPnr",e,"error")
    end
  end
  
  #提取pnr形成web订单
  def self.saveWebOrderByPnr(pnr,uid,eterm_name,eterm_pswd)
    begin
      logger.error "============ 代理人提取pnr ================"
      pnr = pnr.upcase #转大写
      user = WebUser.find_by_id(uid)
      result = "提取失败"
      res = getRtPnrResult(pnr,eterm_name,eterm_pswd)
      if res.index("ENTIRELY CANCELLED")
        result = "#{pnr}已经取消"
      elsif res.index(pnr)
        res = res.gsub(/\r/,"")
        res = res.gsub(/\n/,"<br>")
        res = res.gsub(/ {2,}/," ")
        res = res.gsub(/ \+{1,}/,"")
        res = res.gsub(/ \-{1,}/,"<br>")  #替换+-号为换行
        res = res.strip
        logger.error "-----res="
        logger.error res
        
        if res.index("SSR INFT") || res.index("XN/IN/")
          result = "该pnr包含婴儿票,不能提取"
        else
          pass_nameArr = Array.new
          cardArr = Array.new
          baby_nameArr = Array.new
          baby_dateArr = Array.new

          air_noArr = Array.new
          positionArr = Array.new
          fromtoArr = Array.new
          fly_dateArr = Array.new
          arr_timeArr = Array.new
          fly_timeArr = Array.new
          status_typeArr = Array.new
          priceArr = Array.new
          ticketNoArr = Array.new

          seat = 1 #座位数 婴儿不占座
          res1 = res[0,res.index(". ")+2]
          flght_no = res1[res1.rindex("<br>")+4..-1].to_i
          logger.error "flght_no="+flght_no.to_s
          seat = flght_no-1
          res2 = res[res1.rindex("<br>")+4..-1]

          logger.error "-----乘客姓名res1="
          logger.error res1
          for i in 1..flght_no-1
            logger.error "-----第"+i.to_s+"位乘客"
            if i>9
              startNum = res1.index(i.to_s+".")+3
            else
              startNum = res1.index(i.to_s+".")+2
            end
            endNum = res1.index((i+1).to_s+".")-1
            res3 = res1[startNum..endNum]
            logger.error "---"+res3+"---"
            res3 = res3[0,res3.index(" ")] if res3.index(" ")
            res3 = res3.gsub(/<br>/,"").strip
            logger.error "---"+res3+"---"
            eval("pass_nameArr[#{i-1}] = res3")
          end

          logger.error "-----res2="
          logger.error res2
          toYear = Time.new.strftime("%Y").to_s
          air_no_num = 0
          while(res2.index("<br>"))
            res3 = res2[0,res2.index("<br>")].strip
            logger.error  "-----行结果="+res3
            if res3.index(". ") && res3.rindex(" ")>30
              logger.error "#航班信息"
              num = air_no_num
              res4 = res3[res3.index(" ")+1..-1]
              air_no = res4[0,res4.index(" ")]
              air_no = air_no[1..-1] if air_no.index("*")
              logger.error air_no
              eval("air_noArr[#{num}] = air_no")

              res4 = res4[res4.index(" ")+1..-1]
              position = res4[0,res4.index(" ")]
              logger.error position
              eval("positionArr[#{num}] = position")

              res4 = res4[res4.index(" ")+1..-1]
              res5 = res4[0,7]
              #TH28AUG 转化成2008-09-09的形式
              m = getMonthByStr(res5[4,3])
              fly_date = toYear+"-"+m+"-"+res5[2,2]
              logger.error fly_date
              eval("fly_dateArr[#{num}] = fly_date")

              if res4.index(" ")>9
                #日期和城市对中间没有空格
                if res4[7,2].to_i>0
                  #乘机日期中带有年份
                  res4 = res4[9..-1]
                else
                  res4 = res4[7..-1]
                end
              else
                res4 = res4[res4.index(" ")+1..-1]
              end
              if res4.index(" ")>6
                #城市对和状态中间不是空格
                fromto = res4[0,6]
                logger.error fromto
                status_type = res4[7,2]
                logger.error status_type
                seat = res5[9..-1].to_i
                logger.error seat
              else
                fromto = res4[0,res4.index(" ")]
                logger.error fromto
                res4 = res4[res4.index(" ")+1..-1]
                res5 = res4[0,res4.index(" ")]
                status_type = res5[0,2]
                logger.error status_type
                seat = res5[2..-1].to_i
                logger.error seat
              end
              eval("fromtoArr[#{num}] = fromto")
              eval("status_typeArr[#{num}] = status_type")

              res4 = res4[res4.index(" ")+1..-1]
              fly_time = res4[0,res4.index(" ")]
              fly_time = fly_time[0,2]+":"+fly_time[2,2]
              logger.error fly_time
              eval("fly_timeArr[#{num}] = fly_time")

              res4 = res4[res4.index(" ")+1..-1]
              arr_time = res4[0,res4.index(" ")]
              arr_time = arr_time[0,2]+":"+arr_time[2,2]
              logger.error arr_time
              eval("arr_timeArr[#{num}] = arr_time")

              positionPrice = PositionPrice.find(:first,:conditions=>["fromto=? and position=?",fromto,position])
              if positionPrice && positionPrice.price
                price = positionPrice.price
              else
                price = 0
              end
              logger.error price
              eval("priceArr[#{num}] = price")

              air_no_num += 1
            elsif res3.index(".TL")
              logger.error "#时限"
              res4 = res3[res3.index("/")+1..-1]
              tktl_time = res4[0,res4.index("/")]
              #tktl_time = tktl_time[0,2]+":"+tktl_time[2,2]
              logger.error tktl_time
              res4 = res4[res4.index("/")+1..-1]
              res5 = res4[0,res4.index("/")]
              logger.error res5
              #06AUG 转化为2008-09-09格式
              m = getMonthByStr(res5[2,3])
              tktl_date = toYear+"-"+m+"-"+res5[0,2]
              logger.error tktl_date
            elsif res3.index("SSR FOID")
              logger.error "#证件号"
              if res3.index("NI")
                res4 = res3[res3.index("NI")+2..-1]
              elsif res3.index("PPG")
                res4 = res3[res3.index("PPG")+3..-1]
              else
                res4 = ""
              end
              if res4.index("/P")
                res5 = res4[0,res4.index("/")]
                num = res4[res4.index("/P")+2..-1].to_i
                logger.error num
                logger.error res5
                num -= 1
                eval("cardArr[#{num}] = res5")
              end
            elsif res3.index("TN/")
              logger.error "#票号"
              res4 = res3[res3.index("TN/")+3..-1]
              if res4.index("/P")
                num = res4[res4.index("/P")+2..-1].to_i
                res5 = res4[0,res4.index("/P")]
                logger.error num
                logger.error res5
                num -= 1
                eval("ticketNoArr[#{num}] = res5")
              end
            elsif res3.index("SSR INFT")
              logger.error "#婴儿出生年月日"
              res4 = res3[res3.rindex(" ")+1..-1]
              if res4.index("/P")
                res5 = res4[0,res4.index("/")]
                logger.error res5
                #12FEB08 转化成2008-09-09的形式
                m = getMonthByStr(res5[2,3])
                baby_date = "20"+res5[5,2]+"-"+m+"-"+res5[0,2]
                logger.error baby_date
                num = res4[res4.index("/P")+2..-1].to_i
                logger.error num
                num -= 1
                eval("baby_dateArr[#{num}] = baby_date")
              end
            elsif res3.index("XN/IN/")
              logger.error "#婴儿姓名"
              res4 = res3[res3.index("XN/IN/")+6..-1]
              res5 = res4[0,res4.index("INF")]
              logger.error res5
              if res4.index("/P")
                num = res4[res4.index("/P")+2..-1].to_i
                logger.error num
                num -= 1
                eval("baby_nameArr[#{num}] = res5")
              else
                baby_nameArr[0] = res5
              end
            end
            res2 = res2[res2.index("<br>")+4..-1]
          end

          logger.error ">>>>>>>>>>>>>>>>>>"
          logger.error pass_nameArr
          logger.error cardArr
          logger.error baby_nameArr
          logger.error baby_dateArr
          logger.error air_noArr
          logger.error positionArr
          logger.error fromtoArr
          logger.error fly_dateArr
          logger.error arr_timeArr
          logger.error fly_timeArr
          logger.error status_typeArr
          logger.error ticketNoArr

          transaction do #事务
            insurance_number = 0
            if air_noArr.length>0
              go = true
              link_man = ""
              link_tel = ""
              link_email = ""
              link_address = ""
              tktl_time = "" if tktl_time==nil
              tktl_date = nil if tktl_date==nil
              price_sum = 0
              logger.error "=====循环航班====="
              for j in 0..air_noArr.length-1
                logger.error "---第#{j}个航班"
                airNo = air_noArr[j]
                logger.error airNo
                fromto = fromtoArr[j]
                fly_date = fly_dateArr[j]
                fly_time = fly_timeArr[j]
                arr_time = arr_timeArr[j]
                price = priceArr[j]
                fuel_tax = CommonHelper.getFuelTax(fromto)
                rake_off = 0
                #TODO 计算返利
                logger.error price
                price_sum = price.to_i*pass_nameArr.length
                chd_price = CommonHelper.getChdPrice(airNo[0,2],fromto)
                
                orderid = WebOrder.saveWebOrder(uid.to_i,pnr,airNo,fromto,fly_date,fly_time,arr_time,position,"",link_man,link_tel,link_email,link_address,price_sum,seat,insurance_number,tktl_date,tktl_time,rake_off)
                if orderid
                  logger.error "===订单id="+orderid.to_s
                  ticketidArr = Array.new
                  logger.error "乘客个数="+pass_nameArr.length.to_s
                  logger.error "======循环乘客======"
                  0.upto(pass_nameArr.length-1) do |i|
                    logger.error "第"+i.to_s+"个乘客="+pass_nameArr[i]
                    passenger_name = pass_nameArr[i]
                    if cardArr[i]
                      logger.error "证件="+cardArr[i]
                      id_card = cardArr[i]
                    else
                      id_card = ""
                    end
                    airdrome_tax = 50
                    if passenger_name.index("CHD")
                      logger.error chd_price
                      tid = WebTicket.saveWebTicket(orderid,pnr,passenger_name,"",id_card,chd_price,0,fuel_tax/2,insurance_number)
                    else
                      logger.error price
                      tid = WebTicket.saveWebTicket(orderid,pnr,passenger_name,"",id_card,price,airdrome_tax,fuel_tax,insurance_number)
                    end
                    
                    if tid
                      ticketidArr.push(tid)
                      #logger.error "===票id数组==="
                      #logger.error ticketidArr
                    else
                      go = false
                      result = "保存航班信息失败,航班号是#{airNo},乘客是#{passenger_name}"
                      #如果失败，删除记录
                      delWebOrderTicket(orderid)
                    end
                  end

                  if go
                    #更新订单总金额
                    tickets = WebTicket.find_by_sql("select sum(total_price) as price_sum from web_tickets where web_order_id="+orderid.to_s+" and is_locked<>1")
                    price_sum = tickets[0].price_sum
                    logger.error "订单总金额="+price_sum.to_s
                    WebOrder.update_all("price_sum="+price_sum.to_s,["id=?",orderid])
                    
                    result = orderid.to_s
                  end
                else
                  result = "保存订单信息失败,请检查pnr中信息是否正确"
                end
              end
            else
              result = "该pnr中没有航班信息"
            end
          end #结束事务
        end
      else
        result << ","+res
      end
      return result
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","saveWebOrderByPnr",e,"error")
    end
  end

  #得到各航空公司折扣代码对应的折扣数
  def self.getAllDiscountHash
    begin
      hash = Hash.new
      airways = Airways.find(:all)
      airways.each do |airway|
        #positions = Position.find(:all,:conditions=>["airways_id=?",airway.id])
        positions = airway.positions
        if positions && positions.length>0
          chash = Hash.new
          positions.each do |position|
            chash[position.position_code] = position.discount
          end
          hash[airway.airways_code] = chash
        end
      end
      return hash
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getAllDiscountHash",e,"error")
    end
  end

  #得到某个航空公司舱位代码对应的折扣
  def self.getDiscountHash(airway_code)
    begin
      #logger.error  "============CommonHelper getDiscountHash("+airway_code+")================"
      hash = Hash.new
      airway = Airways.find_by_code(airway_code)
      if airway
        #positions = Position.find(:all,:conditions => ["airways_id=?",airway.id])
        positions = airway.positions
        if positions && positions.length>0
          positions.each do |position|
            hash[position.position_code] = position.discount
          end
        end
      end
      return hash
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getDiscountHash",e,"error")
      return Hash.new
    end
  end

  #得到某个航空公司折扣代码对应的折扣
  def self.getDiscountArray(airway_code)
    begin
      airway = Airways.find_by_code(airway_code)
      if airway
        #positions = Position.find(:all,:conditions => ["airways_id=?",airway.id])
        arr = airway.positions
      end
      arr = Array.new if arr==nil
      return arr
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getDiscountArray",e,"error")
    end
  end

  #得到一个字符的舱位号，例如东航MU的航班的Y90类型的舱位号处理成B舱
  def self.getOneCharDiscountCode(airway_code,discount_code)
    begin
      return discount_code if discount_code.length==1
      result = ""
      airway = Airways.find(:first,:conditions => ["airways_code=?",airway_code])
      if airway
        if discount_code.index("Y") && discount_code.index("Y")==0
          discount_code = discount_code[1..discount_code.length]
          position = Position.find(:first,:conditions => ["airways_id=? and discount=?",airway.id,discount_code])
          result = position.position_code
        end
      end
      return result
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getOneCharDiscountCode",e,"error")
    end
  end

  #翻译AVH查询航班的结果
  def self.translateAvhResult(res)
    begin
      return "" if res==nil || res==""
      #res = res.gsub(/\n\d. *\*{0,}/,"<br>")        #替换回车和数字以及后面的+-号、空格、*等为<br> 使每一行的航班号前面都没有其他任何东西
      res = res.gsub(/\n\d. /,"<br>")
      res = res.gsub(/  -- T\d/,"")                  #去掉航站楼的信息 例如 -- T3
      res = res.gsub(/  T\d -- /,"")                 #去掉航站楼的信息 例如 T3 --
      res = res.gsub(/  -- \d/,"")                   #去掉 -- 3
      res = res.gsub(/\+{1,}/,"").gsub(/\-{1,}/,"")  #去掉+-号
      res = res[res.index("<br>")+4..-1]             #去掉第一行
      if res.index("**")
        res = res[0,res.index("**")]                 #去掉最后一行
      end
      res = res.gsub(/\n */,"-----")                 #替换第二段舱位信息之前的换行为-----
      res = res.strip
      #转换后的字符串必须以<br>结尾
      res << "<br>" if res[res.length-4..-1].index("<br>")==nil
      return res
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","translateAvhResult",e,"error")
    end
  end

  #得到某航班或者航空公司在某个航段内的所有舱位价格记录
  def self.getPositionPriceHash(air_no,fromto)
    begin
      hash = Hash.new
      air_no = air_no.gsub(/^\*/,"") #去掉航班前面的*
      airways_code = air_no[0,2]
      #不包括特殊舱位
      sql = " and (special is null or special<>'yes')"
      #      #先找不是该航班的公共价格
      #      ppArr = PositionPrice.find(:all,:conditions=>["fromto=? and airways_code=? and airNo<>? "+sql,fromto,airways_code,air_no])
      #      if ppArr && ppArr.length>0
      #        for pp in ppArr
      #          hash[pp.position] = pp #舱位是key 对象是value
      #        end
      #      end
      #      #再找专属与该航班的价格
      #      ppArr = PositionPrice.find(:all,:conditions=>["fromto=? and airNo=? "+sql,fromto,air_no])
      #      if ppArr && ppArr.size>0
      #        for pp in ppArr
      #          hash[pp.position] = pp #舱位是key 对象是value
      #        end
      #      end
      ppArr = PositionPrice.find(:all,:conditions=>["fromto=? and airways_code=? "+sql,fromto,airways_code],:order=>"price")
      for pp in ppArr
        hash[pp.position] = pp #舱位是key 对象是value
      end
      return hash
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getPositionPriceHash",e,"error")
      return Hash.new
    end
  end

  #得到某航班或者航空公司在某个航段内的所有舱位价格记录,以对象的形式返回。这样可以排序，HASH不可以排序
  def self.getPositionPriceRecords(air_no,fromto)
    begin
      air_no = air_no.gsub(/^\*/,"") #去掉航班前面的*
      airways_code = air_no[0,2]
      #不包括特殊舱位
      sql = " and (special is null or special<>'yes')"
      ppArr = PositionPrice.find(:all,:conditions=>["fromto=? and airways_code=? "+sql,fromto,airways_code],:order=>"price",:select=>"position,price",:order=>"price")
      return ppArr
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getPositionPriceHash",e,"error")
      return nil
    end
  end
  
  #得到某个航段的所有特殊舱位
  def self.getSpecialPositionHash(airways_code,fromto,fly_date)
    begin
      hash = Hash.new
      fly_date = Time.new.strftime("%Y-%m-%d") if fly_date==nil
      sql = " and special is not null and special='yes' and (start_date is null or start_date<='"+fly_date+"') and (end_date is null or end_date>='"+fly_date+"')"
      ppArr = PositionPrice.find(:all,:conditions=>["fromto=? and airways_code=? "+sql,fromto,airways_code])
      if ppArr && ppArr.size>0
        for pp in ppArr
          hash[pp.air_no+","+pp.position] = pp #舱位是key 对象是value
        end
      end
      return hash
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getSpecialPositionHash",e,"error")
      return Hash.new
    end
  end

  #刷新某个航班或者航空公司在某个航段上的舱位价格记录
  def self.refreshPositionPrice(rubySocket,air_no,fromto,date,ename,pswd)
    begin
      #logger.error  "=============CommonHelper refreshPositionPrice==============="
      hash = Hash.new
      air_no = air_no.gsub(/^\*/,"")
      airways_code = air_no[0,2]
      date = Time.new.strftime("%d%b%y") if date==nil
      y_price = 0 #经济舱Y舱价格

      #rubySocket = SocketHelper.getSocket(ename,pswd) if rubySocket==nil
      if rubySocket
        cmd = "fd:"+fromto+"/"+airways_code
        #logger.error  "-----cmd="+cmd
        res = SocketHelper.getCR(rubySocket,cmd,false)
        #logger.error "-----FD命令结果-----"
        #logger.error  res
        if res.index("FD:")
          res = res.gsub(/\r/,"")
          res = res.gsub(/\n/,"<br>")
          res = res.gsub(/ {1,}/," ")
          #logger.error "----- while start 循环开始-----"
          num=0
          while res.index("<br>")
            res1 = res[0,res.index("<br>")].strip
            #logger.error  "---Line---"
            #logger.error  res1
            if res1.index("PAGE ")
              break
            elsif num>0
              ######## 分析 #######
              res2 = res1[res1.index("/ ")+2..-1].strip
              price = res2[0,res2.index("=")].strip
              #logger.error  "price="+price
              res3 = res2[res2.index("/")+1..-1].strip
              positionInfo = res3[0,res3.index(" ")].strip
              #logger.error  "positionInfo="+positionInfo
              position = positionInfo[0,1]
              #logger.error  "position="+position
              if position=="Y"
                y_price = price.to_i
              end
              positionPrice = PositionPrice.new()
              positionPrice.airways_code = airways_code
              positionPrice.air_no = air_no
              positionPrice.fromto = fromto
              positionPrice.position = position
              positionPrice.price = price.to_i
              if !positionPrice.save
                infoLogger(nil,nil,"Common_Helper","refreshPositionPrice","save #{air_no} #{fromto} position #{position} Price failed","error")
              end
              hash[position] = positionPrice
            end
            res = res[res.index("<br>")+4..-1].strip
            num += 1
          end
          #logger.error "----- while end 循环结束-----"
          #FD命令最低只能查到45折，4折及以下通过折扣计算票价
          airway = Airways.find_by_code(airways_code)
          if airway && y_price>0
            positions = Position.find(:all,:conditions=>"discount<45 and discount>0 and airways_id="+airway.id.to_s)
            for pm in positions
              position = pm.position_code
              discount = pm.discount
              if discount>0
                #logger.error  "....................."+position+"舱 "+pm.discount.to_s+"折"
                price = getRightPrice((y_price*discount)/100)
                #logger.error price
                #保存舱位价格
                positionPrice = PositionPrice.new()
                positionPrice.airways_code = airways_code
                positionPrice.air_no = air_no
                positionPrice.fromto = fromto
                positionPrice.position = position
                positionPrice.price = price.to_i
                if !positionPrice.save
                  infoLogger(nil,nil,"Common_Helper","refreshPositionPrice","save #{air_no} #{fromto} position #{position} Price failed","error")
                end
                hash[position] = positionPrice
              end
            end
          end
          #使用pat:a命令获取燃油税
          fuelTax = FuelTax.find(:first,:conditions=>["fromto=?",fromto])
          if fuelTax==nil
            server = Constants::SERVER_INFO
            res1 = SocketHelper.getCR(rubySocket,"i",false)
            #logger.error  res1
            if server.index("pek4")
              res1 = "OK#"
            else
              res1 = SocketHelper.getCR(rubySocket,"lock",false)
              #logger.error  "res1="+res1
            end
            if res1.index("OK#")
              cmd = "ss:"+air_no+"Y"+date+fromto+"1"
              #logger.error  "-----"+cmd
              res2 = SocketHelper.getCR(rubySocket,cmd,true)
              #logger.error  "res2="+res2
              cmd = "pat:a"
              #logger.error  "-----"+cmd
              res3 = SocketHelper.getCR(rubySocket,cmd,true)
              #logger.error  "res3="+res3
              #更新航段燃油费
              if res3.index("YQ:CNY")
                res4 = res3[res3.index("YQ:CNY")+6..-1]
                tax = res4[0,res4.index(".")].to_i

                fuelTax = FuelTax.new
                fuelTax.fromto = fromto
                fuelTax.tax = tax
                fuelTax.save

                fuelTax = FuelTax.new
                fuelTax.fromto = fromto[3,3]+fromto[0,3]
                fuelTax.tax = tax
                fuelTax.save
              end
            end
          end
        end
      end
      #logger.error  "========== refreshPositionPrice END ==============="
      return hash
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","refreshPositionPrice",e,"error")
      rubySocket.close if rubySocket
      return Hash.new
    end
  end

  #保存退票信息
  def self.saveDrawTicket(uid,tid,draw_money,remark)
    begin
      remark = "退票" if remark==nil || remark==""
      draw_money = draw_money.to_i
      transaction do
        ticket = Ticket.find_by_id(tid)
        order = ticket.order

        sql = " order_id="+ticket.order_id.to_s+" and passenger_id="+ticket.passenger_id.to_s
        sql << " and status <> '"+Constants::TICKET_STATUS_YQX+"' and status <> '"+Constants::TICKET_STATUS_YTP+"' and status <> '"+Constants::TICKET_STATUS_YZF+"'"
        tickets = Ticket.find(:all,:conditions=>sql + " and is_locked<>1 ")
        #保险不退
        for ticket in tickets
          #ticket.other = draw_money
          #ticket.total_price = insurance_number*Constants::DEFAULT_INSURANCE_PRICE
          ticket.canceler_id = uid.to_i
          ticket.cancel_date = Time.new
          ticket.cancel_reason = remark + " 退票费为"+draw_money.to_s
          ticket.status = Constants::TICKET_STATUS_YTP
          ticket.point = 0
          ticket.save
          #维护订单总价格 减去除保险外的费用
          order.price_sum -= ticket.total_price - ticket.insurance_number*Constants::DEFAULT_INSURANCE_PRICE
        end

        #加上退票费 减去乘客人数
        order.price_sum += draw_money
        order.seat -= 1
        if order.seat==0
          #没有其他不是已退票状态的票记录，则订单也成为已退票状态
          order.status = Constants::ORDER_STATUS_YTD
          order.canceler_id = uid.to_i
          order.cancel_date = Time.new
          order.cancel_reason = remark
        end
        if order.save
          return true
        end
      end
      return false
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","saveDrawTicket",e,"error")
      return false
    end
  end

  #保存团体票乘客
  def self.saveGroupPassenger(orderid,passStr,eterm_name,eterm_pswd)
    begin
      info = "操作失败"
      order = Order.find_by_id(orderid) if orderid
      if order
        pnr = order.pnr
        logger.error pnr
        ticket = order.tickets[0]
        air_no = ticket.air_no
        logger.error air_no
        transaction do #事务
          nmStr = "nm"
          cardStr = ""
          no = 1
          passArr = passStr.split(";")
          for pass in passArr
            logger.error pass
            itemArr = pass.split(",")
            i=0
            for item in itemArr
              if i==1
                pass_name = item
                pass_name_cmd = SocketHelper.getTransChineseName(item)
                nmStr << "1"+pass_name_cmd
              elsif i==2
                human_type = item
              elsif i==3
                card = item
                if human_type=="成人" && card!=""
                  cardStr << Constants::SEPARATE_KEY if cardStr!=""
                  cardStr << "SSR FOID "+air_no[0,2]+" HK/NI"+card+"/P"+no.to_s
                end
              elsif i==4
                birthday = item
                date_cmd = CommonHelper.getCmdDateFormat(item) if item!=""
                if human_type=="儿童"
                  nmStr << "("+date_cmd+")"
                end
              end
              i += 1
            end
          
            new_ticket = Ticket.new
            new_ticket.attributes.each do |attr, value|
              eval("new_ticket.#{attr} = ticket.#{attr}") if attr!="id"
            end
            #得到常旅客id
            passenger = Customer.find(:first,:conditions => ["name=? and card=? and is_locked<>1",pass_name,card])
            if passenger==nil
              #不是常旅客
              passenger = Customer.new
              passenger.name = pass_name
              passenger.card = card
              passenger.birthday = birthday
              passenger.customer_type_id = 1 #1表示为常旅客
              passenger.save
            end
            new_ticket.passenger_id = passenger.id
            new_ticket.save
                    
            no += 1
          end

          rubySocket = SocketHelper.getSocket(eterm_name,eterm_pswd)
          if rubySocket
            res = SocketHelper.getCR(rubySocket,"i",false)
            cmd = "rt"+pnr
            logger.error "-----命令cmd="+cmd
            res = SocketHelper.getCR(rubySocket,cmd,true)
            logger.error "-----返回结果res="+res
            if res.index("ENTIRELY CANCELLED")
              info = "#{pnr}已经被取消"
            elsif res.index(" "+pnr)
              cmd = nmStr
              logger.error "-----穿入姓名命令cmd="+cmd
              res = SocketHelper.getCR(rubySocket,cmd,true)
              logger.error "-----返回结果res="+res
              if res.index(" "+pnr)
                cmd = cardStr
                logger.error "-----穿入证件命令cmd="+cmd
                res = SocketHelper.getCR(rubySocket,cmd,true)
                logger.error "-----返回结果res="+res
                if res.index(" "+pnr)
                  res = SocketHelper.getCR(rubySocket,"@",true)
                  logger.error "-----封口结果res="+res
                  if res.index(pnr)
                    info = "穿入乘客信息成功"
                  else
                    info = "封口失败,返回信息"+res
                  end
                else
                  info = "穿入证件号失败,返回信息"+res
                end
              else
                info = "穿入姓名失败,返回信息"+res
              end
            else
              info = "提取#{pnr}失败,返回信息"+res
            end
            if rubySocket
              rubySocket.close
              rubySocket=nil
            end
          else
            info = "连接放大器失败,或用户已被占用!"
          end
          if info.index("成功")
            #如果成功 删除所有未指定人员的ticket记录
            Ticket.delete_all("order_id="+orderid+" and passenger_id=1")
            order.group += "满员"
            order.save
          else
            #如果不成功 删除所有已经添加的常旅客信息
            Ticket.delete_all("order_id="+orderid+" and passenger_id<>1")
          end
        end
      else
        info = "获取订单失败"
      end
      return info
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","saveGroupPassenger",e,"error")
      SocketHelper.closeSocket(rubySocket)
      return "失败"
    end
  end
  
  #根据航段获取燃油税
  def self.getFuelTax(fromto)
    begin
      tofrom = fromto[3,3]+fromto[0,3]
      fuelTax = FuelTax.find(:first,:conditions=>["fromto=? or fromto=?",fromto,tofrom])
      tax = fuelTax.tax if fuelTax
      tax = Constants::DEFAULT_FUEL_TAX if tax==nil
      return tax
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getFuelTax",e,"error")
    end
  end

  #根据机型得到机场建设税
  def self.getPlaneTax(plane)
    begin
      planeTax = PlaneTax.find_by_plane(plane)
      airdrome_tax = planeTax.tax if planeTax && planeTax.tax
      airdrome_tax = Constants::DEFAULT_AIRDROME_TAX if airdrome_tax==nil
      return airdrome_tax
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getPlaneTax",e,"error")
    end
  end

  #从订票返回结果中获取pnr
  def self.getStatusTypeFrom(res)
    begin
      #logger.error res
      status_type = ""
      i = 0
      while(res.index(" "))
        i += 1
        #logger.error "第"+i.to_s+"个循环"
        value = res[0,res.index(" ")].strip
        #logger.error value
        if value.length==3 && i>3
          status_type = value[0,2]
          break
        end
        res = res[res.index(" ")+1..-1].strip
      end
      return status_type
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getStatusTypeFrom",e,"error")
      return ""
    end
  end

  #处理订票返回结果 返回带有pnr和航班信息的串
  def self.getPnrFromSocketResult(restr,airNo,airNo2,airNo3,airNo4)
    begin
      result = ""
      if restr && airNo
        restr = restr.gsub(/\r/,"")
        restr = restr.gsub(/\n/,"<br>")
        restr = restr.gsub(/ {1,}/," ")
        restr = restr.strip
        #个别航班号例如：MU774在订票成功后返回信息里面是MU 774的形式
        airNo_special = airNo[0,2]+" "+airNo[2..-1]
        if restr.index(airNo)
          airNo_num = restr.index(airNo)
        elsif restr.index(airNo_special)
          airNo_num = restr.index(airNo_special)
        end
        #第二个航班
        if airNo2 && airNo2!=""
          airNo_special2 = airNo2[0,2]+" "+airNo2[2..-1]
          if restr.index(airNo2)
            airNo_num2 = restr.index(airNo2)
          elsif restr.index(airNo_special2)
            airNo_num2 = restr.index(airNo_special2)
          end
        end
        #第三个航班
        if airNo3 && airNo3!=""
          airNo_special3 = airNo3[0,2]+" "+airNo3[2..-1]
          if restr.index(airNo3)
            airNo_num3 = restr.index(airNo3)
          elsif restr.index(airNo_special3)
            airNo_num3 = restr.index(airNo_special3)
          end
        end
        #第四个航班
        if airNo4 && airNo4!=""
          airNo_special4 = airNo4[0,2]+" "+airNo4[2..-1]
          if restr.index(airNo4)
            airNo_num4 = restr.index(airNo4)
          elsif restr.index(airNo_special4)
            airNo_num4 = restr.index(airNo_special4)
          end
        end
        if airNo_num
          if restr.index("EOT SUCCESSFUL")
            #带有 EOT SUCCESSFUL 信息的形式 航班信息可能在前也可能在后 但pnr一定和 EOT SUCCESSFUL 在一行
            res = restr[0,restr.index("EOT SUCCESSFUL")]
            res = res[res.rindex("<br>")+4..-1].strip if res.rindex("<br>") #如果EOT SUCCESSFUL在航班信息后面
            pnr = res[0,res.index(" ")]
            result = pnr

            res = restr[airNo_num..-1].strip
            res = res[0,res.index("<br>")].strip if res.index("<br>") #第一个航班的行内容
            status_type = getStatusTypeFrom(res)
            result << " "+status_type
            #如果有第二个航班
            if airNo_num2
              res1 = restr[airNo_num2..-1].strip
              res1 = res1[0,res1.index("<br>")].strip if res1.index("<br>") #带有第二个航班信息的行内容
              status_type2 = getStatusTypeFrom(res1)
              result << " "+status_type2 if status_type2!=""
            end
            #如果有第三个航班
            if airNo_num3
              res1 = restr[airNo_num3..-1].strip
              res1 = res1[0,res1.index("<br>")].strip if res1.index("<br>") #带有第三个航班信息的行内容
              status_type3 = getStatusTypeFrom(res1)
              result << " "+status_type3 if status_type3!=""
            end
            #如果有第四个航班
            if airNo_num4
              res1 = restr[airNo_num4..-1].strip
              res1 = res1[0,res1.index("<br>")].strip if res1.index("<br>") #带有第二个航班信息的行内容
              status_type4 = getStatusTypeFrom(res1)
              result << " "+status_type4 if status_type4!=""
            end
          elsif airNo_num==0 || (restr.index("*")==0 && airNo_num==1)
            #以航班信息开头的形式
            res = restr[airNo_num..restr.index("<br>")-1].strip #第一个航班信息的行内容
            #得到订票状态
            status_type = getStatusTypeFrom(res)
            #如果有第二个航班
            if airNo_num2
              res1 = restr[airNo_num2..-1]
              if res1.index("<br>")
                res2 = res1[res1.index("<br>")+4..-1].strip  #带有pnr的行内容
                res1 = res1[0,res1.index("<br>")].strip #带有第二个航班信息的行内容
              end
              status_type2 = getStatusTypeFrom(res1)
              if airNo_num3
                res1 = restr[airNo_num3..-1].strip
                if res1.index("<br>")
                  res1 = res1[0,res1.index("<br>")].strip #带有第三个航班信息的行内容
                end
                status_type3 = getStatusTypeFrom(res1)
              end
              if airNo_num4
                res1 = restr[airNo_num4..-1].strip
                if res1.index("<br>")
                  res2 = res1[res1.index("<br>")+4..-1].strip  #带有pnr的行内容
                  res1 = res1[0,res1.index("<br>")].strip #带有第四个航班信息的行内容
                end
                status_type4 = getStatusTypeFrom(res1)
              end
            else
              res2 = restr[restr.index("<br>")+4..-1].strip  #下一行内容
            end
            if res2.length==5
              pnr = res2
              result = pnr
              result << " "+status_type
              result << " "+status_type2 if status_type2 && status_type2!=""
              result << " "+status_type3 if status_type3 && status_type3!=""
              result << " "+status_type4 if status_type4 && status_type4!=""
            elsif res2.index(" ") && res2.index(" ")==5
              pnr = res2[0,5]
              result = pnr
              result << " "+status_type
              result << " "+status_type2 if status_type2 && status_type2!=""
              result << " "+status_type3 if status_type3 && status_type3!=""
              result << " "+status_type4 if status_type4 && status_type4!=""
            end
          end
        else
          result = restr
        end
      end
      return result
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getPnrFromSocketResult",e,"error")
      return ""
    end
  end

  #取消pnr
  def self.getCancelPnrResult(pnr,eterm_name,eterm_pswd)
    begin
      logger.error  "-----getCancelPnrResult 取消#{pnr}的结果-----"
      if pnr && pnr!=""
        reason = "cancel"
        server = Constants::SERVER_INFO
        rubySocket = SocketHelper.getSocket(eterm_name,eterm_pswd)
        if rubySocket
          if server.index("pek4")
            res = SocketHelper.getCR(rubySocket,"i",false)
            res = "OK#"
          else
            #第一次lock
            res = SocketHelper.getCR(rubySocket,"lock",false)
          end
          if res.index("OK#")
            pnr = pnr.upcase #转大写
            cmd = "rt"+pnr
            logger.error  "-----提取命令="+cmd
            res1 = SocketHelper.getCR(rubySocket,cmd,true)
            logger.error  "-----提取结果="+res1
            if res1.index("NO PNR")
              result = "NO PNR"
            elsif res1.index("*THIS PNR WAS ENTIRELY CANCELLED*")
              result = "该PNR已经被取消"
            elsif res1.index(pnr)
              if server.index("pek4")
                res2 = "OK#"
              else
                #第二次lock
                res2 = SocketHelper.getCR(rubySocket,"lock",false)
                logger.error  "-----LOCK结果="+res2
              end
              if res2.index("OK#")
                cmd = "xepnr@/"+reason
                logger.error  "-----取消命令="+cmd
                res3 = SocketHelper.getCR(rubySocket,cmd,true)
                logger.error  "-----返回结果="+res3
                if res3.index("PNR CANCELLED")
                  if res3.index(pnr)
                    result = "取消#{pnr}成功"
                  else
                    res3 = res3.strip
                    res4 = res3[res3.rindex(" ")..-1]
                    result = "放大器串线造成取消PNR错误,请妥善保存被误取消的PNR:<font color=red>#{res4}</font>"
                  end
                else
                  result = "取消PNR失败,返回信息:"+res3
                end
              else
                result = "LOCK失败"
              end
            else
              result = "提取pnr失败,返回信息:"+res1
            end
          else
            result = "LOCK失败"
          end
          rubySocket.close
        else
          result = "连接放大器失败,或用户"+eterm_name.to_s+"已被占用!"
        end
      else
        result = "PNR不存在"
      end
      return result
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getCancelPnrResult",e,"error")
      rubySocket.close if rubySocket
      return "操作失败,失败原因请查询日志文件"
    end
  end

  #取消pnr中某个乘客的乘机记录
  def self.getCancelTicketResult(pnr,name,eterm_name,eterm_pswd)
    begin
      logger.error  "===== CommonHelper getCancelTicketResult ====="
      pnr = pnr.upcase
      result = "操作失败"
      if pnr && name
        rubySocket = SocketHelper.getSocket(eterm_name,eterm_pswd)
        if rubySocket
          server = Constants::SERVER_INFO
          if server.index("pek4")
            res = SocketHelper.getCR(rubySocket,"i",false)
            res = "OK#"
          else
            res = SocketHelper.getCR(rubySocket,"lock",false)
          end
          if res.index("OK#")
            cmd = "rt"+pnr
            logger.error  "-----命令cmd="+cmd
            res = SocketHelper.getCR(rubySocket,cmd,true)
            logger.error  "-----返回结果res="+res
            if res.index("NO PNR") || res.strip==""
              result = "NO PNR"
            elsif res.index("*THIS PNR WAS ENTIRELY CANCELLED*")
              result = "该PNR已经被取消"
            else
              res = res.gsub(/\r/,"")
              res = res.gsub(/\n/,"<br>")
              res1 = res.gsub(/ {1,}/," ")
              logger.error  "-----整理后结果res1="+res1
              if res1.index("."+name)
                #成人或者儿童
                no = res1[res1.index("."+name)-1,1]
                logger.error  "no="+no
                if no.to_i>0
                  if server.index("pek4")
                    res2 = "OK#"
                  else
                    res2 = SocketHelper.getCR(rubySocket,"lock",false)
                    logger.error  "-----LOCK结果res2="+res2
                  end
                  if res2.index("OK#")
                    cmd = "xep/"+no
                    logger.error  "-----取消命令cmd="+cmd
                    res3 = SocketHelper.getCR(rubySocket,cmd,true)
                    logger.error  "-----返回结果res3="+res3
                    #判断res3的返回结果是否是成功 返回结果中没有该乘客的姓名 没有取消的编号
                    if res3.index(" "+pnr) && res3.index(no+".")==nil && res3.index("."+name)==nil
                      res4 = SocketHelper.getCR(rubySocket,"@",false)
                      logger.error  "-----返回封口结果res4="+res4
                      if res4.index(pnr)
                        result = "操作成功"
                      else
                        result = "封口失败,返回信息:"+res4
                      end
                    else
                      result = "取消编号为"+no+"的乘客"+name+"的票失败,返回信息:"+res3
                    end
                  else
                    result = "LOCK失败"
                  end
                else
                  result = "获取乘客#{name}的编号失败"
                end
              elsif res1.index("/"+name)
                # 10.XN/IN/张儿INF(FEB08)/P1
                # 先获取有婴儿中文名行的内容,从中提取P1编号
                res2 = res1[0,res1.index("/"+name)]
                res2 = res1[res2.rindex("<br>")+4..-1].strip
                res2 = res2[0,res2.index("<br>")].strip
                logger.error "婴儿行内容="+res2+"="
                father_no = res2[res2.index("/P")+2..res2.length]
                logger.error  "father_no="+father_no
                no = res2[0,res2.index(".")]
                logger.error  "no="+no
                if no.to_i>0
                  #循环获取SSR和OSI的编号
                  while(res1.index("SSR INFT") || res1.index("OSI YY 1INF"))
                    flag = 1
                    if res1.index("SSR INFT")
                      res2 = res1[0,res1.index("SSR INFT")]
                    else
                      res2 = res1[0,res1.index("OSI YY 1INF")]
                      flag = 2
                    end
                    res3 = res1[res2.rindex("<br>")+4..-1].strip
                    res4 = res3[0,res3.index("<br>")].strip
                    logger.error "行结果res4="+res4+"="
                    if res4.index("/P"+father_no)
                      ssr_no = res4[0,res4.index(".")] if flag==1
                      osi_no = res4[0,res4.index(".")] if flag==2
                    end
                    res1 = res3[res3.index("<br>")+4..-1].strip
                  end
                  logger.error "ssr_no="+ssr_no
                  logger.error "osi_no="+osi_no
                  if server.index("pek4")
                    res2 = "OK#"
                  else
                    res2 = SocketHelper.getCR(rubySocket,"lock",false)
                    logger.error  "-----LOCK结果res2="+res2
                  end
                  if res2.index("OK#")
                    cmd = "xe"+no
                    cmd << "/"+ssr_no if ssr_no && ssr_no.to_i>0
                    cmd << "/"+osi_no if osi_no && osi_no.to_i>0
                    logger.error  "-----取消婴儿票命令cmd="+cmd
                    res3 = SocketHelper.getCR(rubySocket,cmd,true)
                    logger.error  "-----取消婴儿票返回结果res3="+res3
                    if res3.index(" "+pnr) && res3.index("/"+name)==nil
                      res4 = SocketHelper.getCR(rubySocket,"@",false)
                      if res4.index(pnr)
                        result = "取消婴儿票成功"
                      else
                        result = "取消婴儿票封口失败,返回信息:"+res4
                      end
                    else
                      result = "取消编号为"+no+"的婴儿"+name+"的票失败,返回信息:"+res3
                    end
                  else
                    result = "LOCK失败"
                  end
                else
                  result = "获取婴儿#{name}的编号失败"
                end
              else
                result = "提取PNR信息中没有乘客#{name}的姓名记录"
              end
            end
          else
            result = "LOCK失败"
          end
          if rubySocket
            rubySocket.close
            rubySocket=nil
          end
        else
          result = "连接放大器失败,或用户"+eterm_name.to_s+"已被占用!"
        end
      else
        result = "PNR不存在"
      end
      return result
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getCancelTicketResult",e,"error")
      rubySocket.close if rubySocket
      return "操作失败,失败原因请查询日志文件"
    end
  end

  def self.changeCardIdByPnr(pnr,name,old_card,id_card,eterm_name,eterm_pswd)
    begin
      logger.error  "=====CommonHelper changeCardIdByPnr====="
      result = "失败"
      if pnr && name && id_card
        rubySocket = SocketHelper.getSocket(eterm_name,eterm_pswd)
        if rubySocket
          server = Constants::SERVER_INFO
          if server.index("pek4.")
            res = SocketHelper.getCR(rubySocket,"i",false)
            res = "OK#"
          else
            #第一次lock
            res = SocketHelper.getCR(rubySocket,"lock",false)
          end
          if res.index("OK#")
            cmd = "rt"+pnr
            logger.error  "-----提取命令cmd="+cmd
            res = SocketHelper.getCR(rubySocket,cmd,true)
            #下一页
            res2 = SocketHelper.getCR(rubySocket,"pn",true)
            res << "\r\n"+res2 if res2.index(" "+pnr)==nil
            
            logger.error  "-----提取结果res="+res
            if res.index("NO PNR")
              result = "该PNR不存在"
            elsif res.index("*THIS PNR WAS ENTIRELY CANCELLED*")
              result = "该PNR已经被取消"
            elsif res.index(" "+pnr)
              #res1 = res.gsub(/\n\d/,"<br>")
              res = res.gsub(/\r/,"")
              res = res.gsub(/\n/,"<br>")
              #res1 = res.gsub(/ {2,}/," ")
              res1 = res.squish
              logger.error  "-----整理后结果res1="+res1

              if res1.index("."+name)
                no = res1[res1.index("."+name)-1,1]
                logger.error  "乘客编号no="+no
                if res1.index(". ")
                  flight_no = res1[res1.index(". ")-1,1]
                  logger.error  "航班编号flight_no="+flight_no
                  res2 = res1[res1.index(". ")+2..-1]
                  air_no = res2[0,res2.index(" ")]
                  logger.error  "航班号air_no="+air_no
                end
                xe_succ = false
                if old_card
                  if old_card==""
                    logger.error  "----之前没有证件号信息"
                    xe_succ = true
                  else
                    logger.error  "----旧证件号="+old_card
                    if res1.index("NI"+old_card)
                      res2 = res1[0,res1.index("NI"+old_card)]
                      res3 = res1[res2.rindex("<br>")+4..-1].strip
                      ssr_no = res3[0,res3.index(".")].strip
                      logger.error  "-----旧证件编号ssr_no="+ssr_no
                      cmd = "xe"+ssr_no
                      logger.error  "-----取消旧证件命令cmd="+cmd
                      res4 = SocketHelper.getCR(rubySocket,cmd,true)
                      logger.error  "-----取消旧证件结果res4="+res4
                      #判断是否取消成功
                      if res4.index(old_card) && res4.index("XX1")
                        xe_succ = true
                      end
                    end
                  end
                else
                  #如果旧证件号参数不存在 则根据乘客名字获取旧证件号
                  if flight_no && flight_no.to_i>2
                    #有多个乘客，需要根据P1、P2等等编号来获取旧的身份证号
                    if res1.index(".SSR FOID")
                      #得到第一个证件号记录所在行
                      res2 = res1[res1.index(".SSR FOID")-1..-1]
                      logger.error  "-----得到从第一个证件号所在行开始的字串res2="+res2
                      while res2.index(".SSR FOID")
                        res3 = res2[0,res2.index("<br>")].strip
                        logger.error  "----证件信息行内容res3="+res3
                        if res3.index("/P"+no)
                          old_card = res3[res3.index(" NI")+3..res3.index("/P"+no)-1]
                          logger.error  "----旧证件号="+old_card
                          ssr_no = res3[0,res3.index(".")].strip
                          logger.error  "-----旧证件编号ssr_no="+ssr_no
                          cmd = "xe"+ssr_no
                          logger.error  "-----取消旧证件命令cmd="+cmd
                          res4 = SocketHelper.getCR(rubySocket,cmd,true)
                          logger.error  "-----取消旧证件号结果res4="+res4
                          #判断是否取消成功
                          if res4.index(old_card) && res4.index("XX1")
                            xe_succ = true
                          end
                          break
                        end
                        res2 = res2[res2.index("<br>")+4..res2.length]
                      end
                    end
                  else
                    #只有一个乘客
                    if res1.index(".SSR FOID")
                      res2 = res1[res1.index(".SSR FOID")-1..-1]
                      res3 = res2[0,res2.index("<br>")]
                      old_card = res3[res3.index(" NI")+3..res3.index("/P"+no)-1]
                      logger.error  "----旧证件号="+old_card
                      #删除已有证件号命令是否是xe还需要证实，测试返回NEED ES
                      #ssr_no = res3[0..res3.index(".SSR FOID")-1]
                      ssr_no = res1[res1.index(".SSR FOID")-1,1]
                      #TODO是否需要删除原来的错误证件号码？
                      cmd = "xe"+ssr_no
                      logger.error  "-----取消旧证件命令cmd="+cmd
                      res4 = SocketHelper.getCR(rubySocket,cmd,true)
                      logger.error  "-----取消旧证件号结果res4="+res4
                      #判断是否取消成功
                      if res4.index(old_card) && res4.index("XX1")
                        xe_succ = true
                      end
                    else
                      #本来没有证件信息，直接穿入证件信息
                      logger.error  "----没有旧证件信息"
                    end
                  end
                end
                if xe_succ
                  cmd = "SSR FOID "+air_no[0,2]+" HK/NI"+id_card+"/P"+no
                  logger.error  "-----穿入新证件号命令cmd="+cmd
                  res5 = SocketHelper.getCR(rubySocket,cmd,true)
                  logger.error  "-----穿入新证件号结果res5="+res5
                  if res5.index(id_card)
                    #封口
                    res6 = SocketHelper.getCR(rubySocket,"@",true)
                    logger.error "-----封口结果="+res6
                    if res6.index(pnr)
                      result = "穿入新证件号成功"
                    else
                      result = "封口失败"
                    end
                  else
                    result = "穿入新证件号失败"
                  end
                else
                  result = "删除旧的证件号#{old_card}失败"
                end
              else
                result = "获取乘客姓名失败"
              end
            else
              result = "提取失败,提取结果是:"+res
            end
          else
            result = "lock失败 "+res
          end
          rubySocket.close
          rubySocket = nil
        else
          result = "连接放大器失败,或用户"+eterm_name.to_s+"已被占用!"
        end
      else
        result = "参数错误"
        logger.error  pnr
        logger.error  name
        logger.error  id_card
      end
      return result
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","changeCardIdByPnr",e,"error")
      rubySocket.close if rubySocket
      return "操作失败,失败原因请查询日志文件"
    end
  end

  def self.getPlusRatePoint(plus,plus_rate,point)
    begin
      if plus && plus!="" && plus_rate>0
        logger.error  "plus="+plus
        if plus=="加"
          point -= plus_rate
        elsif plus=="减"
          point << plus_rate
        elsif plus=="乘"
          point -= point*plus_rate/100
        elsif plus=="除"
          point -= point*100/plus_rate
        end
        logger.error  "point="+point.to_s
      end
      return point
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getPlusRatePoint",e,"error")
      return point
    end
  end

  def self.getPolicy(airways_id,airNo,fromto,fly_date,position,trip_type)
    begin
      logger.error "======CommonHelper getPolicy========"
      airNo = airNo[1..airNo.length] if airNo.index("*")
      sql = " date_begin<'"+fly_date+"' and date_end>'"+fly_date+"'"
      if airways_id==nil || airways_id.to_i<=0
        airways = Airways.find_by_code(airNo[0,2])
        airways_id = airways.id if airways
      end
      return nil if airways_id==nil
      sql << " and airways_id=" + airways_id.to_s
      sql << " and position like '%"+position+"%'"
      if trip_type=="往返"
        sql << " and (from_to like '%" + fromto + "%' or from_to like '%"+fromto[3,3]+fromto[0,3]+"%')"
        sql << " and trip_type='"+trip_type+"'"
      else
        sql << " and from_to like '%" + fromto + "%'"
        sql << " and trip_type='单程'"
      end
      sql << " and is_locked=0"
      logger.error sql
      policy = Policy.find(:first,:conditions=>sql)
      return policy
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getPolicy",e,"error")
    end
  end

  def self.getNewOrderNo(user_no)
    begin
      #logger.error "======CommonHelper getNewOrderNo========"
      #logger.error user_no
      if user_no==nil
        user_no = "000"
      elsif user_no.length<3
        if user_no.to_i<10
          user_no = "00"+user_no.to_s
        elsif user_no.to_i<100
          user_no = "0"+user_no.to_s
        end
      elsif user_no.length>3
        user_no = user_no[0,3]
      end
      #logger.error user_no
      now = Time.new
      order_no = "FJ"+now.strftime("%y%m%d")+user_no
      order = Order.find(:first,:conditions=>"order_no is not null and order_no like '"+order_no+"%'",:order=>"id desc",:limit=>1)
      if order && order.order_no
        no = order.order_no
        key = no[11,4].to_i+1
        if key<10
          key = "000"+key.to_s
        elsif key<100
          key = "00"+key.to_s
        elsif key<1000
          key = "0"+key.to_s
        else
          key = key.to_s
        end
      else
        key = "0001"
      end
      order_no << key
      #logger.error order_no
      #logger.error "======Ending======"
      return order_no
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getNewOrderNo",e,"error")
    end
  end

  def self.delOrderTicket(orderid)
    begin
      Order.delete_all(["id=?",orderid])
      Ticket.delete_all(["order_id=?",orderid])
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","delOrderTicket",e,"error")
    end
  end

  def self.delWebOrderTicket(orderid)
    begin
      WebOrder.delete_all(["id=?",orderid])
      WebTicket.delete_all(["web_order_id=?",orderid])
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","delWebOrderTicket",e,"error")
    end
  end
  
  #根据月份简拼得到数字月份
  def self.getMonthByStr(str)
    if str=="JAN"
      return "01"
    elsif str=="FEB"
      return "02"
    elsif str=="MAR"
      return "03"
    elsif str=="APR"
      return "04"
    elsif str=="MAY"
      return "05"
    elsif str=="JUN"
      return "06"
    elsif str=="JUL"
      return "07"
    elsif str=="AUG"
      return "08"
    elsif str=="SEP"
      return "09"
    elsif str=="OCT"
      return "10"
    elsif str=="NOV"
      return "11"
    elsif str=="DEC"
      return "12"
    end
  end

  #根据2008-09-09格式的日期得到09SEP08格式的日期
  def self.getCmdDateFormat(date)
    begin
      if date
        date = date.to_s
        if date!="" && date.index("-") && date.rindex("-") && date.index("-")!=date.rindex("-")
          date = date.strip #去掉前后空格
          date = date.to_date.strftime("%d%b%y")
          date = date.upcase #转化成大写
        end
      end
      return date
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getCmdDateFormat",e,"error")
      return ""
    end
  end

  def self.rightAuthorization (rightHash,controllerName,actionName)
    begin
      if rightHash!=nil
        if rightHash[controllerName+"-"+actionName]==nil || rightHash[controllerName+"-"+actionName] !=1
          return "false"
        end
      else
        return "false"
      end
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","rightAuthorization",e,"error")
    end
  end

  #得到儿童票价
  def self.getChdPrice(airways_code,fromto)
    begin
      chd_price = 0
      ############## 获取儿童票价 ##############
      #positionPrice = PositionPrice.find(:first,:conditions=>["airways_code=? and fromto=? and position=?",airways_code,fromto,"Y"])
      positionPrice = PositionPrice.find(:first,:conditions=>["fromto=? and position=?",fromto,"Y"])
      if positionPrice
        chd_price = positionPrice.price/2
        chd_price = getRightPrice(chd_price)
      end
      return chd_price
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getChdPrice",e,"error")
    end
  end

  #得到婴儿票价
  def self.getBabyPrice(airways_code,fromto)
    begin
      baby_price = 0
      ############## 获取儿童票价 ##############
      #positionPrice = PositionPrice.find(:first,:conditions=>["airways_code=? and fromto=? and position=?",airways_code,fromto,"Y"])
      positionPrice = PositionPrice.find(:first,:conditions=>["fromto=? and position=?",fromto,"Y"])
      if positionPrice
        baby_price = positionPrice.price*0.1
        baby_price = getRightPrice(baby_price)
      end
      return baby_price
    rescue Exception => e
      infoLogger(nil,nil,"Common_Helper","getBabyPrice",e,"error")
    end
  end

  #个位数必须为0 有余数四舍五入
  def self.getRightPrice(num)
    num = num.to_i
    yu = num%10
    num -= yu if yu>0 && yu<5
    num += 10 - yu if yu>=5
    return num
  end

  def self.formatBirthdayToDate(birthdayStr)
    if birthdayStr.length == 15
      return "19#{birthdayStr[6,2]}-#{birthdayStr[8,2]}-#{birthdayStr[10,2]}"
    else
      return "#{birthdayStr[6,4]}-#{birthdayStr[10,2]}-#{birthdayStr[12,2]}"
    end
  end

  def self.infoLogger(userID,ipFrom,cName,aName,error,level)
    begin
      errorInfo = ErrorInfo.new
      if userID !=nil
        errorInfo.user_id = userID
      end
      errorInfo.c_name = cName
      errorInfo.a_name = aName
      errorInfo.ip_from = ipFrom
      errorInfo.log_level = level
      errorInfo.rails_version = Rails.version
      errorInfo.rails_env = RAILS_ENV
      errorInfo.content = error
      errorInfo.save
    rescue Exception => e
      logger.error "CommonHelper infoLogger Error!!!:"
      logger.error e
    end
  end

  #  #访问socket
  #  def self.callSocket(cmd,name,pswd)
  #    begin
  #      p = getSocket(name,pswd)
  #      restr = getCR(p,cmd)
  #      p.closeSocket
  #      #closeSocket(p)
  #      return restr
  #    rescue Exception => e
  #      infoLogger(nil,nil,"Common_Helper","callSocket",e,"error")
  #      p.closeSocket() if p
  #    end
  #  end
  #
  #  #得到
  #  def self.getSocket(name,pswd)
  #    begin
  #      if name==nil || name==""
  #        name = Constants::USERNAME
  #      end
  #      if pswd==nil || pswd==""
  #        pswd = Constants::PASSWORD
  #      end
  #      s = Rjb::import("PlaneSocket")
  #      p = s.new(Constants::SERVER_INFO,Constants::SERVER_PORT,name,pswd)
  #      return p
  #    rescue Exception => e
  #      infoLogger(nil,nil,"Common_Helper","getSocket",e,"error")
  #      p.closeSocket() if p
  #    end
  #  end
  #
  #  #得到命令返回结果并转码
  #  def self.getCR(p,cmd)
  #    begin
  #      resultStr = p.getCR(cmd)
  #      #logger.error resultStr
  #      #resultStr = URI.unescape(resultStr)
  #      #logger.error resultStr
  #      return resultStr
  #    rescue Exception => e
  #      infoLogger(nil,nil,"Common_Helper","getCR",e,"error")
  #      p.closeSocket() if p
  #    end
  #  end
  #
  #  #关闭
  #  def self.closeSocket(p)
  #    begin
  #      p.closeSocket if p
  #    rescue Exception => e
  #      infoLogger(nil,nil,"Common_Helper","closeSocket",e,"error")
  #    end
  #  end
end